4

我必须编写一个读取正整数的程序,然后计算并显示前 N 个奇数整数的总和。例如,如果 N 为 4,则程序应显示值 16,即 1 + 3 + 5 + 7。

到目前为止,这是我所拥有的,但我遇到了一堵砖墙,并且希望能在正确的方向上有所帮助。

import acm.program.*;

public class OddIntegers extends ConsoleProgram {

    public void run() {
        println("This program adds the number of odd numbers");
        int n = readInt("Enter a positive number: ");
        int b = 1;
        for (int i = 0; i < n; i++);
            b = b + (b + 2);

        println("The total is " + b);   
    }
}
4

3 回答 3

3

更好地i用于聚合

int b = 0;
for (int i = 0; i < n; i++) {
    b += (2*i + 1);
}

输入 4,结果:16

于 2012-08-05T02:09:29.720 回答
2

首先;for循环末尾删除。

第二次sum用作变量来存储总和并b保持奇数。

int b=1, sum = 0;
for (int i = 1; i <=n; i++){
    sum+=b;
    b+=2;
}
于 2012-08-05T11:29:55.903 回答
1

You have a semicolon right after your for loop so there is no actual code in the loop, also you calculation is wrong, you add an extra value because you start b at one.

int b = 0;
int odd = 1;
for (int i = 0; i < n; i++){
    b = b + odd;
    odd += 2;
}
于 2012-08-05T01:47:48.243 回答