简体   繁体   English

如何找到输入回路中的最低编号?

[英]How to find the lowest number in an input loop?

I have to write a code that tells the user to input 4 number (they could be decimal) and print the average and lowest of those numbers. 我必须编写一个代码,告诉用户输入4个数字(它们可以是十进制),并打印这些数字的平均值和最小值。

So far I have managed to get the average, but I'm having trouble getting the lowest of the numbers. 到目前为止,我已经设法获得了平均值,但是我很难获得最低的数字。

int iteration = 0;
    float number;
    float total = 0;
    float average;
    float lowest;


    Scanner input = new Scanner(System.in);

    while (iteration < 4){
        System.out.println("Enter score : ");
        number = input.nextFloat();

        iteration++;

        total += number;


        }

    average = total / 4;
    System.out.println("The average is: " + average);

You can initialize your lowest with value Float.MAX_VALUE , everytime the user inputs a value, you compare your lowest with the input value and assign the new smaller value to your lowest. 您可以使用值Float.MAX_VALUE来初始化lowest值,每当用户输入一个值时, Float.MAX_VALUE lowest值与输入值进行比较,并将新的较小值分配给最低值。

int iteration = 0;
float number;
float total = 0;
float average;
float lowest = Float.MAX_VALUE;


Scanner input = new Scanner(System.in);

while (iteration < 4){
    System.out.println("Enter score : ");
    number = input.nextFloat();

    iteration++;

    total += number;

    if(number < lowest){
        lowest = number;
    }

}

average = total / 4;
System.out.println("The average is: " + average);
System.out.println("The minimum is: " + lowest);

Try this: 尝试这个:

float minValue = Double.MAX_VALUE;
while(...){
   ...
   number = input.nextFloat();
   minValue = Math.min(minValue, number);
   ...
}

Hope this will help you:). 希望这个能对您有所帮助:)。

Initially define float lowest = some big no . 最初定义float lowest = some big no Now Every time you enter an input compare it with the lowest . 现在,每次输入时,请与lowest输入进行比较。 If the input is less than lowest assign it as lowest , otherwise don't change lowest . 如果输入小于lowest将其指定为lowest ,否则不改变lowest

As said by Olli Zi you can get the min value by using just a simple function Math.min().Moreover for detailed understanding i am providing the code as well. 就像Olli Zi所说的那样,您可以通过使用简单的函数Math.min()来获得最小值。此外,为了进一步理解,我也提供了代码。

    int iteration = 0;
    float number[]=new float[4];
    float total = 0;
    float average;
    float lowest;


    Scanner input = new Scanner(System.in);

    while (iteration < 4){
        System.out.println("Enter score : ");
        number[iteration] = input.nextFloat();
        total += number[iteration];

        iteration=iteration+1;


    }

    average = total / 4;
    System.out.println("The average is: " + average);


    System.out.println(Math.min(Math.min(number[0],number[1]), Math.min(number[2],number[3]))); 

Hope it helps! 希望能帮助到你!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM