2013-03-04 19 views
0

誰能告訴我我的代碼有什麼問題。我正在嘗試創建一個遊戲,讓電腦猜測我輸入的數字。這裏是我的代碼:電腦猜我編號C編程


#include <stdio.h> 
#include <time.h> 
#include <stdlib.h> 

int main(void) { 

int numberGuess = 0; 
int low = 1; 
int high = 100; 
int computerGuess = 0; 

printf("Enter a number, 1 - 100: "); 
scanf("%d", &numberGuess); 

while (computerGuess != numberGuess) 
{ 

    computerGuess = ((high - low) + low)/2; 
    printf("%d ", computerGuess); 

    if (numberGuess > computerGuess) 
    { 
    printf("Your guess was to low \n"); 
    low = computerGuess+1; 
    } 
    else if (numberGuess < computerGuess) 
    { 
    printf("Your guess was to high \n"); 
    high = computerGuess-1; 
} 
    else if (numberGuess == computerGuess) 
{ 
printf("Yess!! you got it!\n"); 
    } 
} 
return 0; 
} 
+5

你爲什麼不告訴我們什麼作品不同於你期望它開始? – 2013-03-04 19:34:19

+0

它是功課嗎? – sschrass 2013-03-04 19:35:07

+0

首先,你的電腦猜測每次都是一樣的,你應該讓它隨機化並在while循環開始之前聲明它。 – ryrich 2013-03-04 19:35:50

回答

0
computerGuess = ((high - low) + low)/2; 

在這裏你只需要添加低,然後imidiately。減去從而使代碼等於

computerGuess = ((high)/2; 

,你總是比較相同的值while循環永不結束。

+0

這應該是一個評論,而不是一個答案(的確,我剛纔發表了同樣的評論)。 – 2013-03-04 19:38:51

+0

@EricJ。嗯...?抱歉沒有看到您的評論。我實際上運行了代碼,並且自己找到了inf循環。 :S – 2013-03-04 19:39:23

+0

那麼,與編輯就變成一個答案... – 2013-03-04 19:39:24

2

這一行:

computerGuess = ((high - low) + low)/2; 

應該是:

computerGuess = (high - low)/2+low; 

你所尋找的是你的高和低(這是一個二進制搜索,但我的數一半當然你知道)。

+0

非常感謝您的幫助,我想我只是累地看到,小錯誤...謝謝 – user2133160 2013-03-04 19:44:45

+0

@ user2133160在那裏,有時候你可以看不到森林裏的樹木。 – 2013-03-04 19:52:16

0

修復代碼:

#include <time.h> 
#include<stdio.h> 
#include <stdlib.h> 

int main(void) { 

int numberGuess = 0; 
int low = 1; 
int high = 100; 
int computerGuess = 0; 

printf("Enter a number, 1 - 100: "); 
scanf("%d", &numberGuess); 

while (computerGuess != numberGuess) 
{ 

    computerGuess = ((high - low)/2 + low); 
    printf("%d ", computerGuess); 

    if (numberGuess > computerGuess) 
    { 
    printf("Your guess was to low \n"); 
    low = computerGuess+1; 
    } 
    else if (numberGuess < computerGuess) 
    { 
    printf("Your guess was to high \n"); 
    high = computerGuess-1; 
} 
    else if (numberGuess == computerGuess) 
{ 
printf("Yess!! you got it!\n"); 
    } 
} 

return 0; 
}