我需要幫助的作業問題。問題如下:「使用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
開始通過正確縮進你的代碼。實際上很難閱讀。 – litelite
平均只是總和/(更高 - 更低) – ControlAltDel
我認爲這個任務意味着使用'while'循環*代替'for循環。你目前的「while」和「do-while」完全沒有必要。 – Keiwan