[英]How do I generate a random number between -1000 and 1000?
美好的一天,
我正在用Java編寫“猜數字”游戲,並且試圖使程序生成-1000到1000之間的數字,但是由於某種原因,它現在僅生成大於1的數字。
我到底在這里做錯了什么? 有人可以幫我嗎?
Random rand = new Random();
int numberToGuess = rand.nextInt((1000 - (-1000) + 1) + (-1000));
int numberOfTries = 0;
Scanner input = new Scanner(System.in);
int guess;
boolean win = false;
System.out.println("Lets begin.");
while (win == false && numberOfTries < 11) {
System.out.println("Insert a number:");
guess = input.nextInt();
numberOfTries++;
if (guess == numberToGuess) {
win = true;
}
else if (guess < numberToGuess) {
System.out.println("Your guess is too low.");
}
else if (guess > numberToGuess) {
System.out.println("Your guess it too high.");
}
}
if (win == true)
System.out.println("You won with " + numberOfTries + " attempts. The hidden number was " + numberToGuess + ".");
else if (numberOfTries == 11) {
System.out.println("You lost. The number was " + numberToGuess + ".");
}
}
}
int numberToGuess = rand.nextInt(2001) -1000;
將括號內的#視為隨機#可以達到的跨度。 將1加到您的跨度中,因為.nextInt上限是唯一的。 然后,您要使用減法將范圍從0到2000轉換為-1000到1000。
int numberToGuess = rand.nextInt((1000 - (-1000) + 1) + (-1000));
您有1000和-1000,所以將使用rand.nextInt()為零
rand.nextInt(2001) -1000;
使用Math.random()
(int)(Math.random() *2001 +1) - 1001
我在下面使用
int numberToGuess = rand.nextInt((1000 - (-1000)) + 1) + (-1000);
而且我得到的結果低於
-727
-971
-339
84
295
498
....
使用另一個隨機數來確定符號。
int numberToGuess = rand.nextInt(1001);
int sign = rand.nextInt(2);
if(sign==0){
numberToGuess*=-1;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.