I need to generate 4 numbers between 20 to 100 and to print all of them . after that i need to print and to know who the random number that his sqrt the closet one to the number that my ''man'' chose on the start . I know what I want to do but I didn't succeed.
public class RandomNumbers {
public static void main(String[] args){
for(int i = 0; i < 5; i++){
System.out.println((int)((Math.random() * 81) + 20));
}
}
}
For each value you need to check the distance with the sqrt
and keep if if better (for 4 values, use a bound of 4 and not 5 in the loop) :
public static void main(String[] args){
int choosen = 6; // Use a Scanner to use user input
double nearestsqrt = Double.MAX_VALUE;
int value, nearest=-1;
for(int i = 0; i < 4; i++){
value = (int)((Math.random() * 81) + 20);
double sqrt = Math.sqrt(value);
if(Math.abs(sqrt-choosen) < Math.abs(nearestsqrt- choosen)){
nearestsqrt = sqrt;
nearest = value;
}
}
System.out.println(nearest);
}
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.