我无法弄清楚这一点..
//Modify the following to sum only the odd numbers from 1 to 100, and compute the average. (Hint: n is an odd number if n % 2 is not 0.)
sum=0;
for (int number = 1; number <= 100; ++number) { // for loop
sum += number; // same as "sum = sum + number"
}
System.out.println(sum);
答案 0 :(得分:2)
您需要测试数字是否为奇数并计算您找到的赔率。
int oddCount = 0;
int sum = 0;
for (int number = 1; number <= 100; ++number) { // for loop
if (number % 2 != 0) {
sum += number;
oddCount++;
}
}
System.out.println(sum / (double) oddCount)
或者,使用
之类的内容跳过偶数值int oddCount = 0;
int sum = 0;
for (int number = 1; number <= 100; number += 2) { // <-- skip the even values.
sum += number;
oddCount++;
}
System.out.println(sum / (double) oddCount)
答案 1 :(得分:0)
鉴于奇数在除以2时余数为1,则不需要if语句:
int oddCount = 0, sum = 0;
for (int n = 1; n <= 100; ++n) { // for loop
oddCount += n % 2;
sum += n * (n % 2);
}
System.out.println(sum / (double) oddCount)
这里的诀窍是n % 2
对于偶数是零,它们对总数没有影响,但对于奇数,它是1,所以这使它们计数。