The other day I posted a program to find the maximum and minimum values from 5 numbers, but since I received advice in the comments, I would like to repost the corrected one. @ LouisS0616 Thank you for your comment ... !!
By the way, I will put the link of the previous article here. https://qiita.com/GARA41679531/items/c81b57a56bfcb28f84a0
In the previous code, the variables min and max were initialized with 0, so when all the input numbers were positive or negative, either the maximum value or the minimum value was output as 0. To improve that, I assigned the first number entered to the variables min and max, and rewrote the code to check the magnitude relationship from there!
package max_min;
import java.util.*;
import java.math.*;
public class Max_Min {
public static void main(String[] args) {
//TODO auto-generated method stub
Scanner scanner=new Scanner(System.in);
double max=0;
double min=0;
int i;
double a;
System.out.println("Find the maximum and minimum values from the five numbers.");
for(i=1;i<6;i++) {
System.out.print(i+"Second number:");
a=scanner.nextDouble();
if(i==1) {
min=a;
max=a;
}else {
if(a<=min) {
min=a;
}else if(a>=max) {
max=a;
}
}
}
System.out.println("The maximum value is"+max+"is.");
System.out.println("The minimum value is"+min+"is.");
}
}
The code above is the actual rewritten code.
Specifically, what I changed is that I am making a program that inputs numbers 5 times using the for syntax, but in that, I used the if syntax to input the first number as the variable min. I am trying to assign it to max.
I tried to enter all negative numbers this time, but I was able to display it properly without the maximum value becoming 0 !!
I realized once again that the improvements are hidden even in the program that I think is perfect! I would appreciate it if you could let me know if there are any improvements in the code I wrote this time! Thank you for reading to the end !!
Recommended Posts