我的做法有什么问题..而逻辑,并继续逻辑

What is wrong with my do...while logic, and continue logic?

本文关键字:继续 问题 什么 我的      更新时间:2023-10-16

我是stackoverflow的新手,对编程也有些陌生,所以请不要介意我对代码格式的糟糕。我的代码有两个问题。

  1. 我的继续语句(如果玩家键入"y"或"Y",我用它来继续循环(不起作用。它仅在正确猜测后终止程序,这导致我:

2.My 继续计数器会超过0而不停止,我只是在程序的逻辑中看不到我的错误。

我看不出我的逻辑有问题。

    #include "stdafx.h"
    #include <iostream>
    #include <iomanip>
    #include <ctime>
    #include <random>
    using namespace std;
    int getNumber(); //random number prototype
    double getScore(); //gets score
    int chances = 7; //chances to guess with
    int main()
    {
    int guess = 0, 
        random;
    char retry = 'y'; //initialize retry to 'y'
    cout << "This is a random number guessing game. " << "You will be guessing between 1-100."
     << "You have 7 chances. Good luck! n n" << endl;

    random = getNumber(); //give the function a variable
  do
  {
    cout << random << "n" << "n";
    chances--;
    cout << "Enter your guess: ";
    cin >> guess;
        if (guess == random)
        {
            cout << "You have won the game! " << "Your score was: " << getScore();
            cout << "Would you like to retry? (Y or N): ";
            cin >> retry;
            if (retry == 'y' || retry == 'Y')
            {
                chances = 7;
                guess = 0;
                getNumber();
                continue; //player can retry the game
            }
            else if (chances == 0)
            {
                cout << "You have no chances left. Retry? (Y or N): ";
                    cin >> retry;
                if (retry == 'y' || retry == 'Y')
                {
                    chances = 7;
                    guess = 0;
                    getNumber();
                    continue;
                }
            }
                return 0;
        }
        else if (guess != random)
            cout << "You got it wrong. n" << "You have: " << chances << " chances left" << endl << endl;
        else
            cout << "Incorrect Input. Please type a number." << endl << endl;
   } while (guess != random);

return 0;
}
 int getNumber()
    {
     unsigned seed = time(0); //seed the random number
     srand(seed);
     int randNum = rand() % 10 + 1; //random number in the range of 1-10
     return randNum;
    }
if (retry == 'y' || 'Y')

这是不正确的逻辑,这就是为什么您的代码无法按照您想要的方式工作的原因。您希望它是:

if (retry == 'y' || retry == 'Y')

在其他 if-else 语句中也修复此逻辑错误。

你会想看看这个

您的continue语句跳到末尾并检查条件 guess != random ,其计算结果为 false 并退出do while。您需要做的是将猜测重置为0等值,以便条件的计算结果为true