如何将给定整数与可能的根进行比较
How to compare the given integer with possible roots
我无法以最好的方式命名问题...我的目标是编写一个从用户那里获取 integer
n 的程序。然后比较两个整数a和b的三次方。
如果 a^3 + b^3 小于或等于给定的输入,我想将每一个可能的计算打印出来给用户。
我的代码如下:
System.out.println("Hi. Please insert an integer: ");
Scanner input = new Scanner(System.in);
int n = input.nextInt();
double root = Math.cbrt(n);
int rootInt = (int) root;
for (int i = 0; i < rootInt; i++){
for (int j = 0; j < rootInt; j++){
if ((Math.pow(i, 3)) + (Math.pow(j, 3)) <= n){
double t = (Math.pow(i, 3) + (Math.pow(j, 3)));
int totalInt = (int) t;
System.out.println(i + "^3" + " + " + j + "^3" + " = " + totalInt );
} else {
}
j++;
}
i++;
}
当我 运行 并输入 30 时,它会打印
0^3 + 0^3 = 0
0^3 + 2^3 = 8
2^3 + 0^3 = 8
2^3 + 2^3 = 16
我做错了什么?
你增加了 j
和 i
两次。这就是为什么您只测试 i
、j
.
的偶数值
如果要更正代码,请从末尾删除 i++, j++
并仅使用 2 for
中的增量。
我无法以最好的方式命名问题...我的目标是编写一个从用户那里获取 integer
n 的程序。然后比较两个整数a和b的三次方。
如果 a^3 + b^3 小于或等于给定的输入,我想将每一个可能的计算打印出来给用户。
我的代码如下:
System.out.println("Hi. Please insert an integer: ");
Scanner input = new Scanner(System.in);
int n = input.nextInt();
double root = Math.cbrt(n);
int rootInt = (int) root;
for (int i = 0; i < rootInt; i++){
for (int j = 0; j < rootInt; j++){
if ((Math.pow(i, 3)) + (Math.pow(j, 3)) <= n){
double t = (Math.pow(i, 3) + (Math.pow(j, 3)));
int totalInt = (int) t;
System.out.println(i + "^3" + " + " + j + "^3" + " = " + totalInt );
} else {
}
j++;
}
i++;
}
当我 运行 并输入 30 时,它会打印
0^3 + 0^3 = 0
0^3 + 2^3 = 8
2^3 + 0^3 = 8
2^3 + 2^3 = 16
我做错了什么?
你增加了 j
和 i
两次。这就是为什么您只测试 i
、j
.
如果要更正代码,请从末尾删除 i++, j++
并仅使用 2 for
中的增量。