在循环中找到最高,最低和平均值

时间:2013-12-13 13:38:16

标签: java while-loop

我知道这可能是我做错了。我希望它在循环结束时打印最小数字等,但它总是打印为最低的零。如何让它不将退出机制设为零作为最低数字。

请问任何建议?

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);            
    }
}

2 个答案:

答案 0 :(得分:7)

您的highestlowest变量都是从0开始。因此,如果您的数字都是负数,那么您的highest为0,错误。如果你的数字都是正数,你将得到lowest 0,错误。

刚开始使用highest = Integer.MIN_VALUElowest = Integer.MAX_VALUE,然后第一次迭代将以正确的highestlowest值结束。

答案 1 :(得分:0)

在更改高值和低值之前,首先检查数字是否为零。

    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);

此外,您需要在循环中对它们进行任何比较之前初始化highestlowest