是的,我知道这里有很多方法。这是任务的一部分。在这个代码中,一切都按预期工作,除了输入等于和<= 100的数字时,“平均”输出是错误的。例如:如果我输入8,10,19并且零输出则输出计数3总和37平均值9.25 ....平均值应为12.3333。现在,如果我输入8,10,99输出是计数3总和117和平均值39这是正确的。为什么它的总和> 100而不是总和&lt; = 100 ???我不明白。我错过了什么?
public static void main(String[] args) {
//Use Main Method for gathering input
float input = 1;
// Declare variable for sum
float theSum = 0;
// Declare variable for average
float average = 0;
// Declare variable for counting the number of user inputs
int counter = 0;
/* Initialize the while loop using an input of 0 as a sentinel value
* to exit the loop*/
while (input != 0) {
if (input!=0){
counter++;
}
input = Float.parseFloat(
JOptionPane.showInputDialog(
null, "Please enter a number. Enter 0 to quit: "));
// Invoke sum method and pass input and summation to sum method
theSum = (sum(input, theSum));
if (theSum > 100)
{
JOptionPane.showMessageDialog(null, "The sum of your numbers "
+ "are greater than 100!");
break;
}
}
// Invoke display method and pass summation, average, and counter variables to it
average = (avg(theSum, counter));
display(theSum, average, counter);
}
public static float sum(float num1, float sum) {
//Add the user's input number to the sum variable
sum += num1;
//Return value of sum variable as new summation variable
return sum;
}
public static float avg(float num1, float num2) {
//Declare and initialize variable for average
//Calculate average
float average = num1 / num2;
//Return value of average variable
return average;
}
public static void display(float sum, float average, int counter) {
/* I am subtracting 1 from variable counter so as not to include the sentinel value
* of 0 that the user had to enter to exit the input loop in the overall count*/
// Display the count, sum, and average to the user
if (sum > 100) {
JOptionPane.showMessageDialog(null, "Count = " + (counter) + ", Sum = " + sum + ", Average = " + average);
}
if (sum <= 100) {
JOptionPane.showMessageDialog(null, "Count = " + (counter - 1) + ", Sum = " + sum + ", Average = " + average);
}
}
}
答案 0 :(得分:4)
原因是你以不同的方式退出while
循环,具体取决于总和。如果总和小于100,即使您输入数字0
到“退出”,您仍然需要额外的时间。说实话,整个循环需要完全重组;一个do...while
循环将更容易阅读和调试。
答案 1 :(得分:0)
你的柜台比必要的大1。除以(counter - 1)
将解决它。
答案 2 :(得分:0)
问题是因为@chrylis提到的退出while循环的方式。因此,如果总和为<= 100
,则计数器为1。但是当你打印它时,你会得到正确的结果,因为你在这里更新了计数器值:
if (sum <= 100) {
JOptionPane.showMessageDialog(null, "Count = " + (counter - 1) + ", Sum = " + sum + ", Average = " + average);
}
正如您在示例中所看到的:
“如果我输入8,10,19并且零以退出输出count 3 sum 37 average 9.25
”
这是因为计数器值为4
(因此平均值为37/4 = 9.25
),但在显示结果时,您将计数器减1,因此计数为3
do-while循环将解决问题,因为最后会检查条件,因此循环将以相同的方式退出<=100
和'&gt; 100`。
do-while
循环将是这样的:
do{
//here goes your code
}while (input != 0);