2014-10-18 74 views
0

我試圖做一個簡單的猜測遊戲,其中計算機應該猜測我選擇的0和100之間的數字。嘗試運行它,如果數字太低,請按1,然後按2如果數字太高。猜測遊戲 - 如何記住猜測範圍

1.如果我選擇50和計算機猜測41,我按1,因爲數量太少41和100之間

2.然後電腦的猜測,說70,我按2,因爲它太高

3.now問題是,下一個計算機應該70和41之間被猜測(先前猜測的數),但它71與0之間的猜測,因此它跳上跳下極端

4之間的所有時間。我不知道如何讓它記住範圍即。此前猜測的數

System.out.print("Enter a number: "); 
Scanner input = new Scanner(System.in); 
int num=input.nextInt(); 
int ans=0; 

Random rand = new Random(); 
int guess=rand.nextInt(100); 

while(guess!=num) { 
    System.out.print("Is it " + guess + " ? "); 
    ans=input.nextInt(); 
    if (ans==1) { 
     guess=rand.nextInt(100-guess+1)+guess; 
    } 
    else if (ans==2) { 
     guess=rand.nextInt(100-guess+1)+0; 
    } 
} 
System.out.print("Computer guessed: " + guess); 

輸出看起來像這樣:

輸入一個數字:50

它是55? 2

是26嗎? 1

是35嗎? 1

是44嗎? 1

它是54嗎? 2

是31嗎? 1

是39嗎? 1

是87嗎? 2

是0嗎? 1

是11嗎? 1

是97嗎? 2

回答

0

這是你所需要的:

System.out.print("Enter a number: "); 
    Scanner input = new Scanner(System.in); 
    int num = input.nextInt(); 
    int ans = 0; 

    Random rand = new Random(); 
    int min = 0; 
    int max = 100; 
    int guess = rand.nextInt(max); 

    while (guess != num) { 
     System.out.print("Is it " + guess + " ? "); 
     ans = input.nextInt(); 
     if (ans == 1) { 
      min = guess + 1; 
     } else if (ans == 2) { 
      max = guess; 
     } 


     guess = rand.nextInt(max - min) + min; 

    } 
    System.out.print("Computer guessed: " + guess); 

輸出樣本:

Enter a number: 50 
Is it 62 ? 2 
Is it 39 ? 1 
Is it 41 ? 1 
Is it 56 ? 2 
Is it 54 ? 2 
Is it 49 ? 1 
Is it 52 ? 2 
Computer guessed: 50 
+0

非常感謝。我已經使用了這個解決方案,因爲它更簡單並且也是完整的。 – djoomla 2014-10-18 13:01:13

+0

@djoomla - 不用客氣,但現在我發現,這是不正確的alghoritm,因爲rand.nextInt中的最大值是「exlusive」,現在它被糾正了。 – libik 2014-10-18 16:49:34

0

您需要兩個變量。一個用於下限,另一個用於上限。

+0

感謝您帕特里夏。 – djoomla 2014-10-18 13:02:46

2

您應該使用2個變量:一個用於上限,另一個用於下限。

while(guess!=num) { 
    System.out.print("Is it " + guess + " ? "); 
    ans=input.nextInt(); 
    if (ans==1) { 
     lowerLimit = guess; // Your new lower limit . 
     guess=lowerLimit+ (upperLimit- lowerLimit) * r.nextInt(); 
    } 
    else if (ans==2) { 
     upperLimit = guess; // Your new upper limit. 
     guess=lowerLimit+ (upperLimit- lowerLimit) * r.nextInt(); 
    } 
} 
+1

非常感謝您的幫助。我已將您的代碼保存到我的算法libraby中。 – djoomla 2014-10-18 13:02:24