【发布时间】:2016-11-15 18:14:37
【问题描述】:
我需要一个家庭作业问题的帮助。问题如下:“使用 while 循环和 do while 循环计算一系列数字的总和和平均值。显示每个循环的结果。”我已经完成了大部分代码,我只是对它的平均部分有问题。这是我目前所拥有的。
import java.util.Scanner;
public class Homework {
public static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
//Get the minimum and maximum values for the range.
System.out.print("Enter the minimum for the range: ");
int number1 = input.nextInt();
System.out.print("Enter the maximum for the range: ");
int number2 = input.nextInt();
int sum = 0;
double average = 0;
while (sum == 0){
//Get the sum
for (int i = number1; i <= number2; i++)
sum = sum + i;
for (int i = number1; i <= number2; i++)
average = sum / i;
System.out.println("(while loop)The sum is " + sum + " and the average is " + average + ".");
}
do {
//reset the sum so it doesn't mess up.
sum = 0;
for (int i = number1; i <= number2; i++)
sum = sum + i;
for (int i = number1; i <= number2; i++)
average = sum / i;
System.out.println("(do-while loop)The sum is " + sum + " and the average is " + average + ".");
} while (sum == 0);
}
}
现在,我的主要问题是尝试获取最小值不是 1 的范围的平均值。只要该范围内的最小值为 1,它就可以正常工作。有什么办法可以得到它使用大于 1 的最小值。
【问题讨论】:
-
从正确缩进代码开始。真的很难读。
-
平均值只是总和/(高 - 低)
-
我认为该任务意味着使用
while循环而不是for循环。您当前的while和do-while完全没有必要。 -
@ControlAltDel 所以本质上是 sum / numberOfElements
-
@litelite 绝对