int score = 0;
int sum = 0;
in count = -1;
while(score != -1){
count++;
sum += score;
System.out.print("输入一个数:");
score = scanner.nextInt();
}
System.out.println("平均:"+ (double)sum/count);
//程序只写关键的一部分
运行后分别输入:90,60,30,结束时输入-1. 程序所得结果为60,
这样算起来count就为3 ,小弟就是不知怎么为3,觉得是2.忘各位大侠指点,万分感激
------解决方案--------------------
首先,第一次进入循环,score=0,count=0,再输入score=90
第二次进入循环,score=90,count=1,再输入score=60
第三次进入循环,score=60,count=2,再输入score=30
第四次进入循环,score=30,count=3,再输入score=-1
最后进入循环判断,由于score=-1,所以退出循环
------解决方案--------------------
int score = 0;
int sum = 0;
in count = -1;
while(score != -1){
count++;
sum += score;
System.out.print("输入一个数:");
score = scanner.nextInt();
}
第一次的时候 score = 0
所以 count++ ; //count = 0 ;
输入90 , score = 90
count++ ; //count = 1 ;
输入60 , score = 60
count++ ; //count = 2 ;
输入30 ,score =30
count++ ; //count = 3 ;
输入 -1 ,不进入 while循环体,所以此时 count = 3 ;
必须注意 ,你的count定义时赋值为 -1 ;
------解决方案--------------------
- Java code
package com.cai;import java.util.Scanner;public class TestAvg { /** * @param args */ public static void main(String[] args) { int score = 0; int sum = 0; int count = -1; Scanner scanner = new Scanner(System.in) ; while (score != -1) { count++; sum += score; System.out.println(score + " --- " + count) ; System.out.print("输入一个数:"); score = scanner.nextInt(); } System.out.println("平均:" + (double) sum / count); }}