【发布时间】:2014-04-21 16:51:24
【问题描述】:
我有这些属于 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;
}
【问题讨论】:
-
TL;DR; '我怎样才能退出 do-while 循环?' 使用
break;、return;甚至exit();语句?? -
表达式
'999'是一个字符文字(甚至是多字符文字,在一些编译器中是扩展),而@987654326 @ 是一个整数变量。任何普通的编译器都会在这种情况下给你很多警告。