虽然开始双骰子程序的循环未正确执行

While loop for beginning craps program is not executing properly.

本文关键字:循环 执行 子程序 开始      更新时间:2023-10-16

我是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 版本所做的那样。