2014-11-02 1 views
0

나는 C + +로 사용자가 1 ~ 100 사이의 숫자를 추측해야하는 코드를 작성한 다음 컴퓨터에 20 개의 질문을 시도하여 해당 숫자를 추측 할 수있는 코드를 작성했습니다. 여기에 제가 작성한 코드가 있습니다 :20 질문 게임

#include <iostream> 
#include <math.h> 

using namespace std; 

int main() 
{ 
int imax; 
char ans; 
int imin; 
int i; 
const char y = 'y'; 
const char n = 'n'; 



imax = 100; 
imin = 0; 
i = 0; 
int e = (imax - imin)/2; 

cout << "Think of a number between 1-100." << endl; 

do 
{ 
    cout << "Is the number equal or greater too " << e << endl; 
    cin >> ans; 
    if (ans == y) 
    { 
     cout << "Is the number " << e << endl; 
     cin >> ans; 
     if (ans == y) 
     { 
      i = e; 
      return i; 
     } 
     else 
     { 
      imin = e; 

     }   
    } 
    else 
    { 
     imax = e; 
    } 

} while (i == 0); 



cout << "Your number is "<< i << endl; 

system("PAUSE"); 

return 0; 
} 

코드는 두 번째 if 문에 도달 할 때까지 작동합니다. 그것은 'y'를 받아 들일 것이고 그 숫자가 e인지 물어볼 것입니다. 그러나 'n'이 대답되면 그것은 또한 imin을 변화시키지 않을 것입니다. 또한 'n'이 첫 번째 if 문에 대해 응답되면 imax도 동일하게 설정되지 않습니다. 나는 이것을 꽤 오랫동안 고민하고 있으며, 주어진 도움을 정말로 감사 할 것입니다.

+1

imin이 바뀌므로 e로 변경됩니다. 'n'에 응답하면 변경되지 않습니다. imin은 (으)로 변경해야하는 대상은 무엇입니까? –

답변

0

EE (273)은 악몽이다.

#include<iostream> 
using namespace std; 

const int MAX_VALUE = 100; 
const int MIN_VALUE = 1; 

int guess; 
int high = MAX_VALUE; 
int low = MIN_VALUE; 

char choice; 

int main(){ 


cout<<"Think about a number between "<<MIN_VALUE<<" and "<<MAX_VALUE<<". \n\n"; 
guess = (high-low)/2; 

while((high-low)!=1){ 
cout<<"Is your number less than or equal to "<<guess<<"? \nEnter y or n. \n\n"; 
cin>>choice; 

if(choice=='y' || choice=='Y') { 
    high = guess; 
    guess -= (high - low)/2; 
} 
else if(choice=='n' || choice=='N') { 
    low = guess; 
    guess += (high - low) /2; 
} 
else cout<<"Incorrect choice."<<endl; 


} 
cout<<"Your number is: "<<high<<".\n"; 

system("pause"); 
return 0; 
} 
+0

나는 그걸로 고민하고 있습니다. 문제를 해결하기 위해 다른 방법을 사용해 주셔서 감사합니다. –

+0

어디서 얻었습니까? 저자에게 크레딧을 줄 필요가 있습니다. –

2

의 값을 루프으로 변경하지 않으므로 else 조건에는 아무런 영향이 없습니다. 또한 논리가 약간 잘못되었습니다. 희망이 도움이됩니다,이 시도 :

#include <iostream> 
#include <math.h> 

using namespace std; 

int main() 
{ 
int imax; 
char ans; 
int imin; 
int i; 
const char y = 'y'; 
const char n = 'n'; 



imax = 100; 
imin = 0; 
i = 0; 

cout << "Think of a number between 1-100." << endl; 

do 
{ 
    int e = imin + ((imax - imin)/2); 
    cout << "Is the number equal or greater too " << e << endl; 
    cin >> ans; 
    if (ans == y) 
    { 
     cout << "Is the number " << e << endl; 
     cin >> ans; 
     if (ans == y) 
     { 
      i = e; 
      break; 
     } 
     else 
     { 
      imin = e; 

     }   
    } 
    else 
    { 
     imax = e; 
    } 

} while (i == 0); 



cout << "Your number is "<< i << endl; 

system("PAUSE"); 

return 0; 
} 
+0

그게 전부 고마워! –

+1

'return i;'는 'break;'로 바꿔야합니다. – drescherjm

+0

지적 해 주셔서 감사합니다 .. 변경됨 ... –