1
public class SumAndAverage {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        int sum = 0;
        int num;
        for(num = 0; num <= 100; num++){ 
            sum += num; 
        }

        double average = ((double)sum) / num;
        System.out.println("The sum is " + sum);
        System.out.println("The average is " + average);

    }
}

结果:

总和为 5050 平均值为 50.0

怎么了:

5050 / 100 = 50.5 不是 50.0

4

3 回答 3

6

当这个循环结束时

for(num = 0; num <= 100; num++){ 

num101,不是100。因为发生的情况是条件被测试直到它为假,而这发生在num>100.

于 2013-10-12T17:59:14.050 回答
0

Variable num will be 101 when it comes out of loop. So you need to manually subtract one or below can do the same job better with one iteration less

for(num = 0; num < 100; ){ 
    sum += ++num; 
}

Full Program

public class SumAndAverage {

public static void main(String[] args) {
    // TODO Auto-generated method stub
    int sum = 0;
    int num;
    for(num = 0; num < 100; ){ 
        sum += ++num; 
    }

    double average = ((double)sum) / num;
    System.out.println("The sum is " + sum);
    System.out.println("The average is " + average);
}
}

Check it.

于 2013-10-12T18:09:15.900 回答
0

你理解错了。当您不使用变量作为循环检查时(以及当您通常使用幻数反模式时)会发生这种情况 - 并在以后重用它们。这样你就可以确定你将实际使用什么值。

public class SumAndAverage {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        int sum = 0;
        int num;
        int max = 100;
        for(num = 0; num <= max; num++){ 
            sum += num; 
        }

        double average = ((double)sum) / max;
        System.out.println("The sum is " + sum);
        System.out.println("The average is " + average);

    }
}

您的 num 等于 101,而不是 100...

于 2013-10-12T18:00:50.583 回答