Java GPA计划问题

时间:2015-11-13 02:16:46

标签: java

我的程序由于某种原因计算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);

2 个答案:

答案 0 :(得分:5)

让我们来看看代码

  • gpa = 0
  • 获取用户输入(用户输入' 2')
  • 现在gpa = 2
  • 总计+ = 2
  • counter ++
  • while(gpa!= 0)// nope,gpa是2
  • 循环回来
  • 获取用户输入(用户输入' 0')
  • 现在gpa = 0
  • 总计+ = 0
  • counter ++ // oops!
  • while(gpa!= 0)//是的,退出循环

但为时已晚,我们已增加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);

如果您还有其他问题,请发表评论。