[英]For-loop returning wrong results
I am getting wrong results resolving below task:我在解决以下任务时得到错误的结果:
Generalized harmonic numbers.广义谐波数。 Write a program GeneralizedHarmonic.java that takes two integer command-line arguments n and r and uses a for loop to compute the nth generalized harmonic number of order r, which is defined by the following formula: formula
编写一个程序 GeneralizedHarmonic.java,它采用两个 integer 命令行 arguments n 和 r 并使用 for 循环计算第 n 次广义谐波数 r,其由以下公式定义:公式
public class GeneralizedHarmonic {
public static void main(String[] args) {
int a = Integer.parseInt(args[0]);
int b = Integer.parseInt(args[1]);
int i;
double sum = 0;
for (i = 0; i <= a; i++) {
sum += 1 / Math.pow(i, b);
}
System.out.println(sum);
}
}
This is my code but I could not get the correct test output.The output result is always Infinity
.这是我的代码,但我无法获得正确的测试 output。output 结果始终为
Infinity
。 test outputs测试输出
You have initliazed int i = 0
in for-loop for (i = 0; i <= a; i++)
and so the first element of your harmonic number isn't你已经在 for-loop
for (i = 0; i <= a; i++)
中初始化了int i = 0
,所以你的调和数的第一个元素不是 , but
, 但
.
.
The code that works:有效的代码:
public class GeneralizedHarmonic {
public static void main(String[] args) {
int a = Integer.parseInt(args[0]);
int b = Integer.parseInt(args[1]);
double sum = 0;
for (int i = 1; i <= a; i++) {
sum += 1 / Math.pow(i, b);
}
System.out.println(sum);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.