找出哪个猜测最接近随机数

时间:2017-10-12 19:42:14

标签: java

鉴于此要求

  

创建一个创建随机数的代码,并要求用户进行2次猜测,然后打印出实际数字,并说明您猜测哪一个最接近

我被困在最后一部分。请帮忙。

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package selectionexercises;

/**
 *
 *
 * @author jhonpaul
 */
import java.util.Scanner;

public class GuessNumber {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("I have picked a number between 1 to 100 try to guess it.");
        int randomNumber = (int) (Math.random() * 100 + 1);
        System.out.println("Enter Your First Guess.");
        int guess1;
        guess1 = sc.nextInt();
        System.out.println("Enter Your Second Guess.");
        int guess2;
        guess2 = sc.nextInt();
        System.out.println("The number was " + randomNumber);
        int range;
        range = randomNumber;



    }
}

2 个答案:

答案 0 :(得分:1)

使用Math.min(Math.abs(randomNumber-guess1),Math.abs(randomNumber-guess2))

答案 1 :(得分:1)

做这样的事情:

//Calculate difference and use absolute value (turn negative values into positive if necessary)
int difference1 = Math.abs(randomNumber - guess1)
int difference2 = Math.abs(randomBumber - guess2)

//Compare result
if(difference1<difference2) {
    System.out.println("Guess1 was closer"); 
} else if (difference1>difference2) {
    System.out.println("Guess2 was closer"); 
} else {
    System.out.println("Both were equally close!"); 
} 

有比此更短的方法,但是scince你是首发我认为这是一种易于理解且易于使用的方式。