-4

可能重复:
取用户输入数的平均值

for (int n1 = in.nextInt(); n1 >= 0; n1 = in.nextInt())
  {
          int total = 0;
          int count = 0;

          while (n1 >= 0)
          {
                  n1 = in.nextInt();
                  total = total + n1;
                  count = count + 1;

          }
          out.println(total);
          out.println(count);
  } 

我想把我输入的所有数字加起来,这个代码正确吗?它只添加了我最后的 2 个输入。我希望循环继续进行,直到用户输入负数,然后循环停止,然后输出我的总数和计数。

Scanner in = new Scanner(System.in);
Printstream out = System.out;
4

2 回答 2

2
int total = 0;
int count = 0;

while (true) {
    int n = in.nextInt();
    if (n < 0) 
        break;
    total += n;
    count ++;
}
out.println(total);
out.println(count);
于 2012-07-31T04:02:45.213 回答
0

您的代码应如下所示。

int total = 0;
int count = 0;
int n1;

try
{
    while((n1=Integer.parseInt(in.nextLine()))>=0)
    {
        total = total + n1;
        count = count + 1;
    }
}
catch(Exception e)
{
    System.out.println(e.toString());
}

out.println("Total     = "+total);
out.println("Count     = "+count);

Format df=new DecimalFormat("#.##");
out.println("Average   = "+df.format((double)total/count));
于 2012-07-31T04:03:25.850 回答