-2
int main()
{
    //declare variables
    int randomNumber = 0;
    int numberGuess  = 0;
    int attempts     = 0;
    int startTime    = 0;
    int endTime           = 0;
    int totalSecond  = 0;
    int upperBound  =  0;
    char gameType   = ' ';
    char again      = 'Y';

    while(again == 'Y' || again == 'y')
    {
        cout <<" Game Type Enter B for Beginner,I for Intermediate, and A for Advanced:";
        cin >> gameType;
        gameType=toupper(gameType);

        if(gameType == 'B')
        {
            cout <<" Guess a number from 1 through 10:";

            upperBound = 10;

        }
        else if( gameType == 'I')
        {
            cout <<" Guess a number from 1 through 100:";

            upperBound = 100;
        }
        else if( gameType == 'A')
        {
            cout <<" Guess a number from 1 through 1000:";

            upperBound = 1000;
        }
        else 
            cout <<" Invalid Game Level:";
        cout << endl;

        //generate a random number

        srand(static_cast<int>(time(0)));
        randomNumber = 1 + rand() % ((upperBound) - 1 + 1);

        //get first number guess from user
        cin >> numberGuess;
        startTime = static_cast<int>(time(0));
        while ( numberGuess != randomNumber)
        {
            if( numberGuess > randomNumber)
            {
                cout <<"Sorry, guess lower:";
                cin >> numberGuess;
            }
            else if ( numberGuess < randomNumber)
            {
                cout <<"Sorry, guess higher:";
                cin >> numberGuess;
            }
            attempts+=1; 

        }
        cout << endl <<" Yes, the number is " << randomNumber <<"." << endl;
        endTime= static_cast<int>(time(0));
        totalSecond = endTime- startTime;
        cout << endl <<" This is how many attempts you took:" << attempts << endl;
        cout << endl <<" This took :" << totalSecond <<" seconds"<< endl;
        cout <<" Do you want to play again? (Y/N)";
        cin >> again;
        cout << endl << endl;
    } 

    system("pause");
    return 0; 
}

私の試みは、各ゲームですべて一緒に加算されます。これはなぜですか?? 1 つのゲームをプレイすると、5 回試行したと表示され、もう一度プレイすると 3 回試行したと表示され、8 回試行したと表示されます。

4

2 に答える 2

3

attemptsループ間でゼロにリセットしていないためです。代わりに、それを宣言するときにゼロに設定します(int attempts = 0;)が、ゼロに戻すために何もせずにループをぐるぐる回し続けます。他のすべての変数も同様にリセットされませんが、ほとんどはコードのセットアップ フェーズで設定されます。

于 2013-04-29T13:19:56.227 に答える