gpt4 book ai didi

java - 使用 Do While 循环的 Java 平均分

转载 作者:行者123 更新时间:2023-12-01 22:03:04 25 4
gpt4 key购买 nike

我正在为学校做一项作业,根据给定的输入计算平均测试成绩。当我输入“-1”时,它不会退出 do/while 循环。当我插入一个值时,计数不会增加,因此平均值无法正确计算。

  1. Create a class called Average.
  2. Try to use separate sections in the main method to declare all variables, get input, do processing, and perform output. Create a comment for each section.
  3. In the declarations section of main, declare an double variable called average.
  4. In the input section of main, display an opening message using JOptionPane that explains the purpose of the program.
  5. In the processing section of main, assign the value of average by calling a method named calcAverage().
  6. Within the calcAverage method, declare int variables count, score, and total, and a double variable called average.
  7. Also in the calcAverage method, use a do-while loop to get scores from the user until the user enters -1 to quit. (Your message to the user should be, "Enter a score or -1 to quit".)
  8. In the calcAverage method, calculate the average score and return that value to the main method.
  9. In the output section of main, display a JOptionPane window that states (for example), "The average of the 5 scores is 75.8."
import javax.swing.JOptionPane;

public class Average {
static int count = 0;

public static void main(String[] args) {
//Declaration section
double average;
//Input Section
calcAverage();
//Processing Section
average = calcAverage();
//Output Section
JOptionPane.showMessageDialog(null, "The average of the " + count + "scores is" + average);
} // end main

public static double calcAverage() {
int count = 0, score = 0, total = 0;
double average;
String input;
do {
input = JOptionPane.showInputDialog("Enter a score or -1 to quit");
score = Integer.parseInt(input);
total = total + score;
count++;
} while (score != -1);
average = (total / count);
return average;
} // end calcAverage
} // end class

最佳答案

您的count calcAverage 中的局部变量正在跟踪 count您声明的变量 staticAverage类,所以static变量永远不会更新;它仍然是 0。不要在 calcAverage 中重新声明此变量.

您正在调用calcAverage两次,并忽略第一次返回的内容。因此,您必须输入 -1两次完成程序。删除第一个calcAverage打电话。

你总是数数,即使 -1输入,因为直到循环结束才检查条件。添加if更新条件totalcount仅当 score不是-1 .

这一行有整数除法:

average = (total / count);

在 Java 中,整数除法会产生一个整数,因此 5 和 6 2 个数字的平均值将是 5,而不是 5.5。 Cast one of them to double .

average = ((double) total / count);

关于java - 使用 Do While 循环的 Java 平均分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33377896/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com