2017-03-21 65 views
0

这个程序不工作,我看不出为什么! 当我猜想一个不是45的数字刚刚停止,它甚至不会给我一个猜测新数字的机会吗?简单的游戏循环与C++

有什么建议吗?

int main() 
{ 

char try_again; 
int count = 5; 
int num; 

cout << "Hello, Guess a number between 1 - 100! You have " << count << " guesses to find the right number!\n"; 
cin >> num; 


while (num != 45); 

{ 
    count--; 

    if (count > 0) 
    { 
     cout << "Wrong number, guess again!\n You have " << count << " guesses left" << endl; 
     cin >> num; 
    } 


    else 
    { 
     cout << "Out of guesses! Try again? y/n\n"; 
     cin >> try_again; 

     if (try_again == 'y' || try_again == 'Y') 
      main(); 

     else if (try_again == 'n' || try_again == 'N') 
      return 0; 

    } 

} 

cout << "Congratz, you guessed right! Play again? y/n\n"; 
cin >> try_again; 

if (try_again == 'y' || try_again == 'Y') 
    main(); 
else if (try_again == 'n' || try_again == 'N') 
    return(0); 

return 0; 
} 
+3

'while(num!= 45);' - 多余的分号 –

+1

不要调用'main()'。这是一个很大的禁忌。 –

+0

为什么?还有,“void”数据类型只有在函数不返回值时才可用? –

回答

3

while循环后分号基本意思是“当条件为真,什么也不做”,如果不采取任何措施,情况永远不会改变。

解决这类问题的方法是在编译时使用-Wall或甚至-Wextra。它仍然会编译,但你会得到一个警告。这里是你的程序的输出,当我编译:

$ g++ foo.cpp -Wall -Wextra 
foo.cpp: In function ‘int main()’: 
foo.cpp:16:3: warning: this ‘while’ clause does not guard... [-Wmisleading-indentation] 
    while (num != 45); 
    ^~~~~ 
foo.cpp:18:3: note: ...this statement, but the latter is misleadingly indented as if it is guarded by the ‘while’ 
    { 
^

如果你想知道为什么这甚至是允许的,其实有它的一些用途。我上面提到,这种情况永远不会改变。这不一定是真实的,因为条件可以通过另一个流程或其他方式改变。例如,我们可以做一个while(!keypressed());等待,直到按下一个键。它也可以用来查找链接列表中的最后一个元素while(ptr && (ptr=ptr->next)->next);

但是除非您知道自己在做什么,否则请勿在循环标题后面加分号。这也适用于for循环。