2014-01-31 67 views
0

好吧,這個程序要求用戶輸入一個下限和上限,對象是程序根據反饋系統(-1,0,1)猜測數字。一切正常,每次我給它反饋時都會編譯它,它會將數字加倍,例如查看輸出。任何幫助將大大可以理解的,因爲由於C猜測遊戲上下界

我還在學習總是開放的建議
#include <stdio.h> 
#include <time.h> 
#include <stdlib.h> 

int main(void) { 

int low; 
int high; 
int Guess; 
int feedback; 


printf("Enter Upper bound number: "); 
scanf("%d", &high); 

printf("Enter lower bound number: "); 
scanf("%d", &low); 

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


while (feedback != 0) 
{ 

printf("my guess is: %d ", Guess); 

printf("What do you think?"); 
scanf("%d", &feedback); 

//guess was too low 
if (feedback == -1) 
{ 
Guess = Guess+1; 
printf("my guess is: %d ", Guess); 

printf("What do you think?"); 
scanf("%d", &feedback); 
} 

//guess was too high 
else if (feedback == 1) 
{ 
Guess = Guess-1; 
printf("my guess is: %d ", Guess); 

printf("What do you think?"); 
scanf("%d", &feedback); 
} 

else if (feedback == 0) 
{ 
printf("I win!\n"); 
} 
} 

return 0; 
} 

輸出:

Enter a upper bound number: 40 
Enter a lower bound number: 20 
my guess is: 30 what do you think? -1 
my guess is: 31 what do you think? -1 
my guess is: 31 what do you think? -1 
my guess is: 32 what do you think? -1 
my guess is: 32 what do you think? -1 
my guess is: 33 what do you think? -1 
my guess is: 33 what do you think? -1 
my guess is: 34 what do you think? -1 
my guess is: 34 what do you think? -1 
my guess is: 35 what do you think? 0 
I win! 

回答

1

建議修改平分每個guesss後的剩餘範圍。

// Initialize 
int feedback = !0; // @Digital_Reality 

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

//guess was too low 
if (feedback == -1) { 
    // Guess = Guess+1; 
    low = Guess+1; 
    Guess = (high + low)/2; 
    .... 

//guess was too high 
else if (feedback == 1) { 
    // Guess = Guess-1; 
    high = Guess-1; 
    Guess = (high + low)/2; 
    .... 
+0

你快!..即將發表評論= 0 :) –

0

Chux是正確的。如果你不想讓你的程序重複自己,那麼你只需在if語句中取出printf和scanf,或者將while循環內的print/scanf帶到外面。

1

把你printfswhile loop.之前反正你有這些內部if

printf("my guess is: %d ", Guess); 
printf("What do you think?"); 
scanf("%d", &feedback); 
while (feedback != 0) 
{ 
    //guess was too low 
    if (feedback == -1) 
    { 

PS:與1或其他+已經數初始化feedback

0

因爲你的循環,你會得到雙倍的輸出。您正在測試輸入,然後在'如果'您打印您的猜測並再次接受輸入。一旦收到輸入,循環將重新啓動並打印猜測和請求輸入的當前值。在你的'如果',只需改變猜測的值,讓循環繼續而不是提示。