为什么我的循环没有重新开始到第一次迭代? C++

Why is my loop not restarting to the first iteration? C++

我正在用 C++ 制作一个骰子游戏。我想知道为什么它不重新启动循环。该游戏是三局两胜制。只要玩家想继续玩,它就应该重新开始循环。但是它只重新启动循环一次。我第二次按 'Y' 或者是,在这种情况下它只是退出程序。

我试过将重启放在嵌套的 while 循环中,但它似乎也不起作用。

restart:    

while ((pWin != 2) && (cWin != 2))
{
    pDice1 = rand() % 6 + 1;
    cDice1 = rand() % 6 + 1;


    cout << "Player score is: " << pDice1 << endl;
    cout << "Computer score is: " << cDice1 << endl;

    if (cDice1 > pDice1) {
        cout << "Computer wins!" << endl << endl;
        cWin++;

    } if (pDice1 > cDice1) {
        cout << "Player wins!" << endl << endl;
        pWin++;
    } if (pDice1 == cDice1) {
        cout << "It's a draw!" << endl << endl;
    } if (pWin > cWin) {
        cout << "Player wins this round! Do you wish to keep playing?" << endl;
        cin >> Y;
        if (Y == 'y') {
            goto restart;
        }
        else {
            exit(0);
        }
    }if (cWin > pWin) {
        cout << "Computer wins this round! Do you wish to keep playing?" << endl;
        cin >> Y;
        if (Y == 'y') {
            goto restart;
        }
        else {
            exit(0);
        }
    }
        
        

}

因为你没有在比赛结束后将 pWin cWin 重置为零。

你应该解决这个问题,但也应该把 goto 变成另一个 while 循环,并把那个 while 循环的核心变成一个函数。

首先,这是你的全部代码吗?我注意到您的大部分变量似乎是在提供的代码块之外声明的。如果是这样,您的“Y”是否被声明为 char 而不是字符串类型以匹配您的条件类型?

当它 returns 到顶部时,您似乎无法将 pWin 和 cWin 设置回零。您可以使用以下方法修复:

restart:    
cWin = 0;
pWin = 0;
while ((pWin != 2) && (cWin != 2))
{
pDice1 = rand() % 6 + 1;
cDice1 = rand() % 6 + 1;


cout << "Player score is: " << pDice1 << endl;
cout << "Computer score is: " << cDice1 << endl;

if (cDice1 > pDice1) {
    cout << "Computer wins!" << endl << endl;
    cWin++;

} if (pDice1 > cDice1) {
    cout << "Player wins!" << endl << endl;
    pWin++;
} if (pDice1 == cDice1) {
    cout << "It's a draw!" << endl << endl;
} if (pWin > cWin) {
    cout << "Player wins this round! Do you wish to keep playing?" << endl;
    cin >> Y;
    if (Y == 'y') {
        goto restart;
    }
    else {
        exit(0);
    }
}if (cWin > pWin) {
    cout << "Computer wins this round! Do you wish to keep playing?" << endl;
    cin >> Y;
    if (Y == 'y') {
        goto restart;
    }
    else {
        exit(0);
    }
}
    
    

}