我的程序由于某种原因计算GPA平均值错误。如果我输入4.0三次,则表示平均GPA为3.0,但应为4.0。有人可以帮我找到问题吗?
//variables
double gpa = 0;
double total = 0;
int counter = 0;
int counter2 = 0;
do
{
String gpaEntry = JOptionPane.showInputDialog("Please enter GPAs:");
gpa = Double.parseDouble(gpaEntry);
if (gpa >= 3.5)
counter2 ++;
total += gpa;
counter ++;
}
while (gpa != 0);
double average = (double) (total/counter);
JOptionPane.showMessageDialog(null, "The Average GPA is: " + average);
JOptionPane.showMessageDialog(null, "Number of students:" + counter2);
答案 0 :(得分:5)
让我们来看看代码
但为时已晚,我们已增加counter
,因此我们的average
计算错误
答案 1 :(得分:0)
错误的是,如果用户输入0,则它运行程序然后退出。
试试这段代码(对不起,我目前没有编辑器,所以你可能需要解决一些小问题。)
//variables
double gpa = 0;
double total = 0;
int counter = 0;
int counter2 = 0;
String gpaEntry = JOptionPane.showInputDialog("Please enter GPAs:");
gpa = Double.parseDouble(gpaEntry);
while (gpa != 0) {
if (gpa >= 3.5)
counter2 ++;
total += gpa;
counter ++;
gpaEntry = JOptionPane.showInputDialog("Please enter GPAs:");
gpa = Double.parseDouble(gpaEntry);
}
JOptionPane.showMessageDialog(null, "The Average GPA is: " + average);
JOptionPane.showMessageDialog(null, "Number of students:" + counter2);
如果您还有其他问题,请发表评论。