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.
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.
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
. Now Every time you enter an input compare it with the lowest
. If the input is less than lowest
assign it as lowest
, otherwise don't change 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.
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!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.