更进一步解释,如果我们给任何一个数加上1,我们就得到下一个值。然后我们需要找出它的平方根。如果我们得到一个整数值,那么我们可以说它是某个数的完全平方。如果我们确认下一个数有一个完全平方数,那么输入的数就是一个阳光数,否则它不是阳光数。
在本文中,我们将看到如何使用java编程语言来检查一个数字是否是阳光数。
展示一些实例给你看instance-1的中文翻译为:实例-1输入的数字是80。
让我们使用阳光数的逻辑来检查一下。
80的下一个值 = 80 + 1 = 81
81的平方根=9
正如我们在这里注意到的,81是9的完全平方。
因此,80是一个阳光的数字。
instance-2的中文翻译为:实例-2输入的数字是48。
让我们使用阳光数的逻辑来检查一下。
48的下一个值 = 48 + 1 = 49
49的平方根=7
正如我们在这里注意到的,49是7的一个完全平方数。
因此,48是一个阳光数。
instance-3的中文翻译为:实例-3输入的数字是122。
让我们使用阳光数的逻辑来检查一下。
122的下一个值= 122 + 1 = 123
123的平方根=11.09053651
正如我们在这里注意到的,123没有一个完美的平方数。
因此,122是一个阳光数。
其他一些阳光数的例子包括3、8、15、24、35、48、63等。
语法要获取一个数字的平方根,我们可以使用java.lang包中的math类中内置的sqrt()方法。
以下是使用该方法获取任意数字的平方根的语法。
double squareroot = math.sqrt(input_vale)
你可以使用math.floor()来找到最接近的整数值。
math.floor(square_root)
算法步骤 1 - 通过初始化或用户输入获取一个整数。
第二步 - 然后我们通过将其加1来找到它的下一个值,并将其存储在另一个变量中。
第三步 - 我们找到下一个值的平方根。
第四步 - 现在我们正在寻找最接近的完全平方根,并将其与下一个平方根值相减。
步骤 5 - 如果减法后的值为零,则我们将得到确认,它是一个整数值,表示下一个值是任意数字的完全平方。
第6步 − 如果我们得到确认下一个数字是一个完全平方数,则打印该数字是一个阳光数,否则它不是一个阳光数。
多种方法我们以不同的方式提供了解决方案。
通过使用静态输入值
通过使用用户定义的方法
让我们逐一查看程序及其输出。
方法一:通过使用静态输入值在这种方法中,程序将初始化一个整数值,然后通过使用算法,我们可以检查一个数字是否是一个阳光数。
example的中文翻译为:示例import java.util.*;public class main{ public static void main(string args[]){ //declare an int variable and initialize with a static value int inputnumber=8; //declare a variable which store next value of input number double next=inputnumber + 1; //find the square root of the next number //store it as double value double square_root = math.sqrt(next); //check whether the square root is a integer value or not //if yes return true otherwise false if(((square_root - math.floor(square_root)) == 0)) //if true then print it is a sunny number system.out.println(inputnumber + is a sunny number.); else //if true then print it is a sunny number system.out.println(inputnumber + is not a sunny number.); }}
输出8 is not a sunny number.
方法二:通过使用用户定义的方法在这种方法中,我们将一个静态值分配为输入数字,并将该数字作为参数传递给一个用户定义的方法,然后在方法内部,通过使用算法,我们可以检查该数字是否是一个sunny数字。
example的中文翻译为:示例import java.util.*;public class main{ public static void main(string args[]){ //declare an int variable and initialize with a static value int inp=15; //call the user defined method inside the conditional statement if(checksunny(inp)) //if true then print it is a sunny number system.out.println(inp + is a sunny number.); else //if true then print it is a sunny number system.out.println( is not a sunny number.); } //define the user defined method static boolean checksunny(int inputnumber){ //declare a variable which store next value of input number double next=inputnumber + 1; //find the square root of the next number // store it as double value double square_root = math.sqrt(next); //check whether the square root is a integer value or not //if yes return true otherwise false return ((square_root - math.floor(square_root)) == 0); }}
输出15 is a sunny number.
在本文中,我们探讨了如何使用三种不同的方法在java中检查一个数字是否是阳性数。
以上就是如何在java中检查一个数字是否为阳光数?的详细内容。