这个代码应该让你选择一个#然后通过告诉你的电脑是低还是高你降低了电脑猜测的范围但是范围似乎没有改变可能有人帮助`在这里输入代码:
int min = 1;
int max = 100;
Scanner i = new Scanner(System.in);
System.out.println("whats the number");
int ans = i.nextInt();
int guess = (int)(Math.random()* 100 + 1);
while(ans != guess)
{
System.out.println(guess);
System.out.println("is that number to high)1 or to low)2");
int p = i.nextInt();
if(p == 1)
{
if(guess < max)
{
max = guess;
guess = (int)(Math.random()*max + min);
}
else
{
guess = (int)(Math.random()*max + min);
}
}
if(p == 2)
{
if(guess > min)
{
min = guess;
guess = (int)(Math.random()*max + min);
}
else
{
guess = (int)(Math.random()*max + min);
}
}
}
System.out.println(guess + " is right");
答案 0 :(得分:0)
我认为您必须更改guess
变量计算方法。
您想要猜测最小值和最大值之间的数字。所以你可以使用this strategy。
guess = rand.nextInt((max - min) + 1) + min;
您可以在下面找到完整的代码:
import java.util.Random;
import java.util.Scanner;
public class NumbersTest {
public static void main(String[] args) {
int min = 1;
int max = 101;
Scanner i = new Scanner(System.in);
System.out.println("whats the number");
int ans = i.nextInt();
Random rand = new Random(); //NOTE
int guess = rand.nextInt((max - min) + 1) + min; //NOTE
while (ans != guess) {
System.out.println(guess);
System.out.println("is that number to high)1 or to low)2");
int p = i.nextInt();
if (p == 1) {
if (guess < max) {
max = guess;
guess = rand.nextInt((max - min) + 1) + min; //NOTE
} else {
guess = rand.nextInt((max - min) + 1) + min; //NOTE
}
}
if (p == 2) {
if (guess > min) {
min = guess;
guess = rand.nextInt((max - min) + 1) + min; //NOTE
} else {
guess = rand.nextInt((max - min) + 1) + min; //NOTE
}
}
}
System.out.println(guess + " is right");
}
}