实现一个以 int 数字为参数的静态方法,使用 Math 类计算给定整数的整数平方根。如果整数为负数,则取正数的平方根,然后返回结果的负数,表示它是虚数
我尝试并到达这里
Scanner in = new Scanner(System.in);
int j = 1, result = 1;
System.out.println("Enter a number : ");
int x = in.nextInt();
if (x == 0 || x == 1 )
{
System.out.println("Square root = " + x);
return;
}
while (result <= x)
{
j++;
result = j * j;
}
System.out.println("Square root = " + (j - 1));
最佳答案
这是您要找的吗?我们找到数字的平方根并确保输入数字为正数。 Math.abs 将求绝对值。如果输入为负数,则返回结果为负数,否则返回平方根。
static int result(int input) {
int result = (int) Math.sqrt(Math.abs(input));
return input < 0 ? -result : result;
}
关于java - 我该如何解决这个程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61409582/