我怎么能退出do-while循环?

时间:2014-04-21 16:51:24

标签: c++ exit-code

我有这些代码块属于NIM减法游戏。我想要实现的是用户只要他/她想要就能玩游戏。如果用户输入999程序将退出,否则用户将一直播放,直到他/她进入999.这是我的代码块。我不确定我是否犯了逻辑错误,或者我需要添加一些特定的退出代码。感谢您的时间和关注。

#include <iostream>
#include <cstdlib>
 using namespace std;

 int main()
 {

int total, n;
while(true){
cout << "Welcome to NIM. \nEnter 999 to quit the game!\nPick a starting total: ";
cin >> total;
if(total==999)
break;

    while(true){
    //pick best response and print results.
    if ((total % 3) == 2)
    {
        total = total - 2;
        cout << "I am subtracting 2." << endl;
    }
    else
    {
        total--;
        cout << "I am subtracting 1." << endl;
    }
    cout << "New total is " << total << endl;
    if (total == 0)
    {
        cout << "I win!" << endl;
        break;
    }
    // Get user’s response; must be 1 or 2.
    cout << "Enter num to subtract (1 or 2): ";
    cin >> n;
    while (n < 1 || n > 2)
    {
        cout << "Input must be 1 or 2." << endl;
        cout << "Re-enter: ";
        cin >> n;
    }
        total = total - n;
        cout << "New total is " << total << endl;
    if (total == 0)
    {
    cout << "You win!" << endl;
    break;
    }
    }
    }
  return 0;
    }

3 个答案:

答案 0 :(得分:1)

您正在修改循环内的total。如果cin>>total,则只需在total==999之后进行测试,如果break,请true进行测试,即

if(total==999)
    break;

并将do-while循环替换为while(true){}

答案 1 :(得分:0)

在do-while循环中,您尝试比较字符文字&#39; 999&#39;变量total,类型为int。

}while(total!='999');

虽然此代码有效,但其结果可能与您预期的不同。具有多个符号的字符文字的值是实现定义的。 你必须写

} while ( total != 999 );

此外,如果玩家将进入999你开始玩他,虽然你必须退出游戏。

所以在我看来,最好使用while循环。例如

while ( true )
{  
   cout << "Welcome to NIM. \nEnter 999 to quit the game!\nPick a starting total: ";

   cin >> total;

   if ( total == 999 ) break;

   // ...
}

答案 2 :(得分:0)

您必须在代码中进行三次更正以使其正确

首先你必须检查总数是否等于999,然后在从用户那里得到总数之后中断你的do循环

秒 - 你必须在你的第一个while循环中加入相同的条件

最后 - 而不是while(total!='999')你应该写while(total!= 999)因为它是整数

相关问题