计算指定范围内的奇数

时间:2018-08-27 14:06:43

标签: java

在此程序中,我如何获得一个计数器以对100以下的奇数进行计数?

public class checkpassfail {

public static void main(String[] args) {
int sum =0;
double avr;
int lower = 1;
int uper = 100;
int num=lower;
 int counter =0;
 while( num <= uper){
     sum= sum+(num+=3);
     counter+=3;
     }


System.out.println("the sum of these nubers is\t" +sum);
System.out.println(counter);
double s =(double)sum;
avr =s/counter;
System.out.println("the average of these nubers is \t"+avr);
}

2 个答案:

答案 0 :(得分:0)

欢迎使用StackOverflow:)

使用for-loop,您可以通过以下方式计算这些汇总值:

final int lower = 1;           // Lower bound
final int upper = 100;         // Upper bound

int sum = 0;                   // Default sum
int count = 0;                 // Default count
double average = Double.NaN;   // Default average

int i = lower;                 // Init the "runnig" variable
while (i <= upper){            // Until the upper bound is reached, do:
     sum += i;                 // Add the number to the overall sum
     count++;                  // One more number has been used - count it
     i += 2;                   // Add 2 since you mind odd values only
}

average = sum / count;         // Calculate the average
                               // And enjoy the results below      

System.out.println("Count: " + count);
System.out.println("Sum: " + sum);
System.out.println("Average: " + average);

还有其他方法可以使用公式来计算规则数字序列的这些特征,或者使用IntStream.range(..)来使用Stream-API,这可以直接计算聚合值。但是,一开始请坚持使用for-loop

答案 1 :(得分:0)

您实际上想做什么?

如果我没记错,您想在 lower_bound upper_bound 之间找到奇数。

int lower_bound = 0, upper_bound = 10;
ArrayList<Integer> odds = new ArrayList<Integer>();

while(lower_bound < upper_bound)
{
    if(lower_bound % 2 == 1)
         odds.add(lower_bound);
    lower_bound++;
}

// Number of odd numbers found
int numberOfOddsFound = odds.size();