如何在我存储的两个变量之间生成随机数

How do I generate a random number between two variables that I have stored?

本文关键字:变量 两个 之间 随机数 存储      更新时间:2023-10-16

可能的重复项:
从范围生成随机整数

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

    #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!nn";

        do
        {
            cout << "Are you ready? (y/n)nn";
            cin >> ready;
            if (ready == 'y')
            {
                do
                {
                    cout << "Is your number " << compGuess << "?nn";
                    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;
    }
最高数字是

最大值应该是多少,最低数字是最小值应该是什么。我需要一个方程,让我生成一个随机数,同时考虑尽可能高和最低的数字。

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

要生成介于最小值和最大值之间的随机数,请使用:

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

(包括最大值和最小值)

真的很快,真的很简单:

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

仅此而已。但是,这偏向于低端,但是如果您使用的是 TR1/C++11 C++您可以使用 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;
}

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

如果你有一个 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++东西总是很高兴......

希望这有帮助- Luke

rand() % ((highestNumber - lowestNumber) + 1) + lowestNumber