[英]Find highest,lowest and average in a loop
I know it's probably something small that I'm doing wrong. 我知道我做错了可能很小。 I want it to print the lowest number etc. at the end of the loop, but it always prints zero as lowest.
我希望它在循环结束时打印出最低的数字等,但它总是将零打印为最低。 How do I get it to not put the exit mechanism zero as the lowest number.
我如何不将退出机制零设为最低数字。
Any advice please? 有什么建议吗?
class HighLowAve
{
public static void main (String[]args)
{
int num =0;
int sum;
int highest;
int lowest;
int index;
Double average;
highest = num;
lowest = num;
sum = 0;
index = 0;
do
{
System.out.println("Enter a number. Press zero to quit ");
num = EasyIn.getInt();
if (num > highest)
{
highest = num;
}
else if (num < lowest)
{
lowest = num;
}
sum = sum + num;
index++;
}while (num !=0);
average = (double) sum/(index-1);
System.out.println("The highest number was " + highest);
System.out.println("The lowest number was " + lowest);
System.out.println("The average number was " + average);
}
}
Your highest
and lowest
variables both start at 0. So if your numbers are all negative, you'll get a highest
of 0, incorrectly. 您的
highest
和lowest
变量都从0开始。因此,如果您的数字全为负,您将错误地获得highest
0。 If your numbers are all positive, you'll get a lowest
of 0, incorrectly. 如果您的数字均为正数,则错误地得到
lowest
的0。
Just start off with highest = Integer.MIN_VALUE
and lowest = Integer.MAX_VALUE
and then the first iteration will end up with the correct highest
and lowest
value. 刚开始时
highest = Integer.MIN_VALUE
, lowest = Integer.MAX_VALUE
,然后第一次迭代将以正确的highest
和lowest
值结束。
First check if the number is zero before changing the high and low values. 在更改高值和低值之前,请先检查数字是否为零。
do
{
System.out.println("Enter a number. Press zero to quit ");
num = EasyIn.getInt();
if (num == 0) break;
if (num > highest)
{
highest = num;
}
else if (num < lowest)
{
lowest = num;
}
sum = sum + num;
index++;
}while (num !=0);
Also you need to initialize highest
and lowest
before you do any comparisons on them in the loop. 同样,在循环中对它们进行任何比较之前,还需要初始化
highest
和lowest
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.