2012-10-22 20 views
0

我想讓一個程序工作,猜測用戶想要的是哪個數字,但是它每次只輸出默認的開關動作。請告訴我我做錯了什麼?謝謝!開關總是輸出默認值猜數字遊戲

srand(time(0)); 
int lowernum = 1; 
int highernum = 1000; 
int number=rand()%highernum + lowernum; 
string letter = ""; 
int letternum = 0; 

cout<<"\nOkay, think of a number between one and 1000 
and I will try to guess it!\n"; 
cout<<"\nIs your number higher (h), lower (l) 
or exactly (e): " << number << "\n"; 
cin>>letter; 

if (letter == "h") 
{ 
    letternum = 1; 
} 
else if (letter == "l") 
{ 
    letternum = 2; 
} 
else if (letter == "e") 
{ 
    letternum = 3; 
} 

switch(letternum){ 
case'1': highernum = number; cout<<"\nIs your number higher (h), 
lower (l) or exactly (e): " << number << "\n"; cin>>letter; 
    break; 
case'2': lowernum = number; cout<<"\nIs your number higher (h), 
lower (l) or exactly (e): " << number << "\n"; cin>>letter; 
    break; 
case'3': cout<<"\nWahoooooo! I win! :D\n"; 
    break; 
default:cout<<"\nI don't understand what you just typed in.\n"; 
    break; 

} 

回答

3

letternum是一個整數,你的開關語句是使用字符(例如 '1'),只是刪除從人物的報價在你的CASE表達式:

switch(letternum){ 
case 1: 

等等

+0

謝謝!我不能相信我錯過了這一點。但是,我的應用程序有另一個問題;它不會得到一個新的隨機數,它只是每次都保持同一個數。任何想法爲什麼? – user1760072

+0

我看不到循環回來生成另一個數字的循環。你是否有一個? – zdan

+0

沒有。我將如何讓程序循環回去?一個while循環在cin上? – user1760072

1

因爲你的交換機標籤是字符,但你的letternum是一個int,所以它們不匹配。