虽然开始双骰子程序的循环未正确执行
While loop for beginning craps program is not executing properly.
我是C++新手,我正在尝试构建一个双骰子程序,该程序将提示用户在赢或输后是否想继续玩。如果选择"是",则它将再次通过循环。如果选择否,则它将显示赢和输的次数。任何帮助将不胜感激。我想我已经看了一段时间了,到了我可能只是我自己的敌人的地步。
#include <iostream>
#include <string>
#include <time.h>
#include <Windows.h>
using namespace std;
int main()
{
char answer(0);
int wins(0), loses(0);
while (answer == 'y'); {
srand(time(NULL)); // one time at the top of the program
int d1(0), d2(0), d3(0), d4(0), roll(0), roll2(0), point(0);
d1 = 1 + (rand() % 6);
d2 = 1 + (rand() % 6);
roll = d1 + d2;
point = d1 + d2;
cout << "Player Rolled " << d1 << "+" << d2 << "=" << roll << endl;
cout << "Point is:" << point << endl;
if (roll == 7 || roll == 11)
{
cout << "Player Rolled " << d1 << "+" << d2 << "=" << roll << endl << "Player Wins" << endl;
wins++;
Sleep(2000); // 2 second pause
cout << "Do you want to play again? (Y or N)";
cin >> answer;
}
else if (roll == 2 || roll == 3 || roll == 12)
{
cout << "Player Rolled " << d1 << "+" << d2 << "=" << roll << endl << "Player loses" << endl;
loses++;
Sleep(2000); // 2 second pause
cout << "Do you want to play again? (Y or N)";
cin >> answer;
}
else
{
do
{
d3 = 1 + (rand() % 6);
d4 = 1 + (rand() % 6);
roll2 = d3 + d4;
if (roll2 == roll)
{
cout << "Player Rolled " << d3 << "+" << d4 << "=" << roll2 << endl << "Player Wins" << endl;
wins++;
Sleep(2000); // 2 second pause
cout << "Do you want to play again? (Y or N)";
cin >> answer;
}
} while (roll2 != 7);
cout << "Player Rolled " << d3 << "+" << d4 << "=" << roll2 << endl << "Player loses" << endl;
loses++;
Sleep(2000); // 2 second pause
cout << "Do you want to play again? (Y or N)";
cin >> answer;
}
}
cout << wins << " Wins and " << loses << " Loses" << endl;
system("pause");
return 0;
}
这是
简化为SSCCE的代码:(见 http://sscce.org(
#include <iostream>
using namespace std;
int main() {
char answer(0);
while (answer == 'y') {
cout << "runningn";
}
cout << "endn";
return 0;
}
http://ideone.com/rsPVP9
所有这些都是打印end
因为答案永远不会设置为"y"。
要使此操作即使运行一次,您应该使用 'y'
而不是 (0)
初始化answer
:
char answer('y');
或者使用do ... while (answer == 'y');
循环。
你关于成为自己的敌人的评论:那时是时候把你的问题归结为更简单的东西了,这样你就可以在你的鞋子里找到石头,就像我在这里对你的代码的 SSCCE 版本所做的那样。
相关文章:
- 在映射擦除c++期间执行循环的次数
- C++-For循环未执行
- 如何强制循环执行另一次迭代到零并关闭循环
- 程序在循环执行后崩溃
- 如何使用两个 for 循环执行唯一的洗牌
- 对于循环执行失败,因为变量我不会递增,为什么?
- pi的倍数到千分之一的值可能会改变循环执行方式
- For 循环执行奇怪的增量跳转
- 在循环执行之间释放内存
- 如何计算循环执行了多少次?C++
- 给定范围内的完美平方:循环执行异常
- 需要澄清有关此循环执行乘法的信息
- 有条件的大平面数组遍历和令人惊讶的短循环执行时间
- c++openmp,用于循环执行期间的循环最大减少值
- 为什么循环执行时间的此C++存在显着差异?
- 对于循环条件内的循环执行,C++
- 使用for循环执行线程
- c++中While循环执行得太早
- c++中while循环执行中的打印输出语句
- 这个 while 循环执行其适当的功能,但对于其他内容是必需的