該程序在用戶播放時似乎與原始程序一樣(實際上,玩這兩個遊戲的人不應該是能夠告訴他們分開)。 在原始程序中,用戶猜測1到100之間的隨機數。在每次猜測後,程序會返回數字是高於還是低於猜測,直到用戶猜測正確爲止。數字猜測遊戲,強制用戶進行最大數量的猜測(Java)
但是,這個程序作弊。與其選擇1-100範圍內的隨機數字,程序根本不會想到隱藏數字,而是以這樣的方式回答 ,以便強制用戶儘可能多地進行猜測。
我該如何做到這一點?我需要做一個if語句的循環嗎?我現在認爲可以做的唯一事情就是做一些其他的事情,我甚至不知道這是否會起作用。
我應該繼續這個內在的if else的想法,但越來越具體嗎?我只是覺得必須有更好的方法。
UPDATE *
好了,所以我想我已經想通了什麼,我最初來的,但現在的程序卡住在一個無限循環當我選擇與猜測相等的上下選擇一個號碼。任何想法爲什麼?
public static int feedback (Scanner console, int guess, int max) {
String sorry = "Sorry, that guess is incorrect.";
String lower = "The number I am thinking of is lower.";
String higher = "The number I am thinking of is higher.";
int guessCount = 0;
guess = console.nextInt();
int upperBound = max + 1;
int lowerBound = 0;
if (guess <= max && guess >= 1) {
guessCount = guessCount + 1;
if (max - guess < guess) {
System.out.println(sorry);
System.out.println(lower);
System.out.print("Your guess? ");
upperBound = guess;
guess = console.nextInt();
guessCount = guessCount + 1;
} else {
System.out.println(sorry);
System.out.println(higher);
System.out.print("Your guess? ");
lowerBound = guess;
guess = console.nextInt();
guessCount = guessCount + 1;
while (upperBound - lowerBound > 2) {
if (guess <= max && guess >= 1) {
if ((lowerBound + ((upperBound - lowerBound)/2)) < guess) {
System.out.println(sorry);
System.out.println(lower);
System.out.print("Your guess? ");
upperBound = guess;
guess = console.nextInt();
guessCount = guessCount + 1;
} else {
System.out.println(sorry);
System.out.println(higher);
System.out.print("Your guess? ");
lowerBound = guess;
guess = console.nextInt();
guessCount = guessCount + 1;
}
} else {
System.out.println("Your guess must be in the range 1-" + max + ". Try again.");
}
}
System.out.println("Yes, the number I was thinking of was " + guess);
}
} else {
System.out.println("Your guess must be in the range 1-" + max + ". Try again.");
return guessCount;
}
return guessCount;
}
從crapton開始! – iluxa
想一下這些限制:任何新的答案都不應該與過去的答案相矛盾。用戶猜測的範圍應該是最大的。然而,對於使用二分搜索的用戶來說,作弊最多會迫使他做log2(n)猜測。 – Tarik
你在這裏正確的軌道上。但請記住,可用的數字範圍不斷變化。如果用戶猜測90並且你的程序顯示「較低」,那麼89是新的最高可能數字;現在排除90到100。同樣,如果用戶猜測20並且程序說「更高」,那麼21是新的最低可能數字。您需要跟蹤最低和最高可能的數字,並且每個猜測都會更改其中一個數字。 – steveha