31

可能重复:
从一个范围内生成随机整数

我正在尝试创建一个程序,让计算机猜测用户在他/她脑海中的数字。唯一需要的用户输入是猜测是否太高、太低或正确。我在根据先前的猜测存储最小值和最大值的两个变量之间生成随机数时遇到问题。这是我的代码:

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

    using namespace std;

    int main()
    {
        srand(static_cast <unsigned int> (time(0)));

        int compGuess = rand() % 100 +1; //Generates number between 1 - 100
        int highestNumber = 100;
        int lowestNumber = 1;
        char ready;
        char highLowSuccess;
        bool success;
        int tries = 0;


        cout << "Please pick a number between 1 - 100. I will guess your number. Don't tell me what it is!\n\n";


        do
        {
            cout << "Are you ready? (y/n)\n\n";
            cin >> ready;

            if (ready == 'y')
            {
                do
                {
                    cout << "Is your number " << compGuess << "?\n\n";
                    cout << "High, Low or Success?";
                    ++tries;
                    cin >> highLowSuccess; //User input telling the computer whether its too high, too low, or a success

                    if (highLowSuccess == 'h') //Executes code if number guessed was too high.
                    {

                        highestNumber = compGuess - 1; //Stores variable indicating the highest possible number based on user input
                        compGuess = rand() % highestNumber +1; //Generates a new random number between 1 and the new highest possible number
                        success = false;
                    }

                    else if (highLowSuccess == 'l') //Executes code if number guessed was too low.
                    {
                        lowestNumber = compGuess + 1;//Stores variable indicating the lowest possible number based on user input
                        compGuess = (rand() % highestNumber - lowestNumber + 1) + lowestNumber // <---- Not producing the desired result
                        success = false;
                    }

                    else if (highLowSuccess == 's') //Executes code if the computer's guess was correct.
                    {
                        cout << "I guessed your number! It only took me " << tries << " tries!";
                        success = true;
                    }


                } while (success != true);
            }


            else
            {
             continue;
            }

       } while (ready != 'y');



    return 0;

    }

highestNumber 是 max 应该是什么,lowestNumber 是 min 应该是什么。我需要一个方程,让我生成一个随机数,同时考虑最高和最低可能的数字。

如果答案真的很简单,请原谅我,我是一个菜鸟程序员。xD

4

4 回答 4

68

要生成介于 min 和 max 之间的随机数,请使用:

int randNum = rand()%(max-min + 1) + min;

(包括最大值和最小值)

于 2012-09-30T01:43:38.393 回答
35

真的很快,真的很容易:

srand(time(NULL)); // Seed the time
int finalNum = rand()%(max-min+1)+min; // Generate the number, assign to variable.

就是这样。但是,这偏向于低端,但是如果您使用的是C++ TR1/C++11,则可以使用random标头来避免这种偏差,如下所示:

#include <random>

std::mt19937 rng(seed);
std::uniform_int_distribution<int> gen(min, max); // uniform, unbiased

int r = gen(rng);

但是您也可以像这样消除普通 C++ 中的偏见:

int rangeRandomAlg2 (int min, int max){
    int n = max - min + 1;
    int remainder = RAND_MAX % n;
    int x;
    do{
        x = rand();
    }while (x >= RAND_MAX - remainder);
    return min + x % n;
}

这是从这篇文章中得到的。

于 2012-09-30T01:56:43.970 回答
24

如果您有 C++11 编译器,您可以使用 c++ 的伪随机数功能为未来做好准备:

//make sure to include the random number generators and such
#include <random>
//the random device that will seed the generator
std::random_device seeder;
//then make a mersenne twister engine
std::mt19937 engine(seeder());
//then the easy part... the distribution
std::uniform_int_distribution<int> dist(min, max);
//then just generate the integer like this:
int compGuess = dist(engine);

这可能更容易掌握,因为您不必做任何涉及模数和废话的事情......虽然它需要更多代码,但了解一些新的 C++ 东西总是很高兴......

希望这会有所帮助 - 卢克

于 2012-09-30T02:04:59.737 回答
7
rand() % ((highestNumber - lowestNumber) + 1) + lowestNumber
于 2012-09-30T01:47:43.860 回答