For loop - 魔术数字程序

时间:2016-10-18 02:07:50

标签: c++ visual-c++

我应该做出哪些更改,以便此代码的用户可以猜测他们选择的幻数的数量,有三种不同的机会猜测每个幻数?我也对改变什么感到困惑,以便一旦用户正确猜出幻数,幻数就会改变。

#include <iostream>
#include <cstdlib>
#include <ctime>
#include <cstdio>

using namespace std;

int main()

{

    int magic; // This is a random number between 1 and 20

    int guess; // This is the guess number being attempted (up to 3 guesses)

    int magicguesses; // This is the amount of magic numbers being guessed attempted

    int i;

    int number; // This is the number the user guessed

    bool numberismagic = false; // This is the flag variable

    unsigned int seed;

    seed = time(NULL);

    srand(seed);

    magic = rand() % 20 + 1;

    cout << "How many magic numbers would you like to guess at today?\n";

    cin >> magicguesses;

    for (i = 1; i < magicguesses + 1; i++)
    {
        cout << "This is trial number:" << i << endl;

        for (guess = 1; (guess < 4) && (!numberismagic); guess++)
        {
            cout << "This is guess number:" << guess << endl;

            cout << "Guess a number between 1 and 20:" << endl;

            cin >> number;

            while ((number < 1) || (number > 20))
            {
                cout << "Your guess is invalid; guess a number between 1 and 20 \n";

                cin >> number;

                cout << endl;
            }

            if (number == magic)
            {
                cout << "You have guessed the magic number correctly! \n";

                numberismagic = true;
            }
            else
            {
                cout << "Sorry - you guessed incorrectly! \n";

                if (number > magic)
                    cout << "Your guess is too high \n" << endl;
                else
                    cout << "Your guess is too low \n" << endl;
            }
        }

        if (number != magic)
            cout << "The magic number is:" << magic << endl;
    }

    return 0;
}

1 个答案:

答案 0 :(得分:1)

我不确定你的第一个问题是什么,但对于这个问题“我也很困惑要改变什么,以便一旦用户正确猜出幻数,幻数就会改变”,你应该编辑变量{ {1}}在第一个<body>内,因此在用户正确猜测或完成尝试后,幻数会发生变化。

magic