这是我的任务:
编写一个程序来读取一个非负整数列表并显示最大整数、最小整数和所有整数的平均值。用户通过输入一个不用于查找最大值、最小值和平均值的负标记值来指示输入的结束。平均值应该是一个类型的值,double
因此它将使用小数部分进行计算。
我已经让不同的部分使用不同的方法:方法 A 使最大值和最小值正确而总和错误,方法 B 使总和和最大值正确而最小值错误。下面的代码演示了方法B。一些变量被注释掉了:
public class testthis2
{
public static void main(String[] args) {
System.out.println("Enter Numbers of Nonnegative Integers.");
System.out.println("When complete, enter -1 to end input values.");
Scanner keyboard = new Scanner(System.in);
//int max = keyboard.nextInt();
int max = 0;
int min = max; //The max and min so far are the first score.
//int next = keyboard.nextInt();
int count = 0;
int sum = 0;
boolean areMore = true;
boolean run_it = false; //run it if its true
//if (max <= -1) {
// System.out.println("Thanks for playing!");
// run_it = false;
//}
// else
// run_it = true;
while(areMore) //always true
{
int next = keyboard.nextInt();
//int max = 0;
// min = max;
if (next < 0) { //if -1 is entered end loop.
areMore = false;
run_it = false;
break;
}
else //run this badboy
if(next >= max)
max = next;
else if(next <= min)
min = next;
run_it = true;
sum += next;
count++;
}
if (run_it = true)
System.out.println("The highest score is " + max);
System.out.println("The lowest score is " + min);
System.out.println("count " + count);
System.out.println("sum " + sum);
System.out.println("average " + (double)(sum/count));
System.out.println("Thanks for playing!");
}
}
当我运行这个测试时,最大值、总和、计数和平均值都是正确的。但是,最小值是错误的,因为显然没有输入 0。这是一个示例测试运行:
When complete, enter -1 to end input values.
37
25
30
20
11
14
-1
The highest score is 37
The lowest score is 0
count 6
sum 137
average 22.0
Thanks for playing!
任何帮助将不胜感激。谢谢!