Java(和奇数和计算平均值)

时间:2014-10-25 02:45:19

标签: java

我无法弄清楚这一点..

//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);

2 个答案:

答案 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,所以这使它们计数。