1

这就是我所拥有的,但它不起作用。当我尝试编译时,我收到此错误消息:

int result = 0;
^^^^^^^^^^^^^^^
无法访问的代码

我的代码:

public int sumOfOddIntegers (int n) {

    if(n < 1);
    return 0;

    int result = 0;
    for(int i = n - 1; i > 0; i--)
    {
        if(i % 2 != 0) {
            result = result + i;
       }
    }
    return result;
}
4

5 回答 5

4
if(n < 1);
    return 0;

相当于:

if(n < 1) {
}

return 0;

它应该被替换为:

if(n < 1)
    return 0;

或(正确的方式)

if(n < 1) {
    return 0;
}
于 2013-04-29T11:50:40.277 回答
3

该声明:

if(n < 1);

由于分号,所以没有操作。无论比较结果如何,都会对比较进行评估,并且什么都不做。

然后,执行下一行,返回 0。

于 2013-04-29T11:50:35.883 回答
0

if(n < 1);是你的问题。其余代码无法访问,因为return'始终执行以下代码。

删除;if(n < 1)

于 2013-04-29T11:51:26.133 回答
0

正如其他人所说,您的 if 语句中的分号是问题所在。但是就个人而言,我会这样做:

public int sumOfOddIntegers (int n) 
{
    int result = 0;

    if(n < 1)
        return result;

    for(int i = 1; i <= n; i += 2)
    {
        result += i;
    }
    return result;
}

这样,您可以将迭代次数减半。我们知道所有其他数字都是奇数,那么为什么还要麻烦迭代偶数并在我们知道它们不是奇数时检查它们是否是奇数呢?

于 2013-04-29T11:54:30.187 回答
0

该序列是一个公差为 2 的算术级数。因此其总和将由公式给出:

总和 = n/2(2a+(n-1)d

其中 n = Math.ceil(k); 其中 k 是给定的数字。并且d = 2,a = 1

public int sumOfOddIntegers (int n) {         

if(n < 1);
return 0;

int totalNumber = Math.ceil(n/2);         

return  (totalNumber/2)*(2 + (totalNumber-1)*2);

`

于 2013-04-30T10:40:36.497 回答