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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12657962/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 16:29:24  来源:igfitidea点击:

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

c++

提问by Jammin

Possible Duplicate:
Generating random integer from a range

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

I am trying to create a program where the computer guesses a number the user has in his/her mind. The only user input required is whether the guess was too high, too low, or correct. I'm having a problem generating a random number between two variables that store the min and max based on previous guesses. Here is my code:

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

    #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 is what the max should be and lowestNumber is what the min should be. I need an equation that lets me generate a random number while taking the highest and lowest possible numbers into account.

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

Forgive me if the answer is really simple, I'm a noob programmer. xD

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

回答by Sidharth Mudgal

To generate a random number between min and max, use:

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

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

(Includes max and min)

(包括最大值和最小值)

回答by Rivasa

Really fast, really easy:

真的很快,很容易:

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

And that is it. However, this is biased towards the lower end, but if you are using C++ TR1/C++11you can do it using the randomheader to avoid that bias like so:

就是这样。但是,这偏向于低端,但是如果您使用的是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);

But you can also remove the bias in normal C++ like this:

但是您也可以像这样删除普通 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;
}

and that was gotten from this post.

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

回答by Jammin

If you have a C++11 compiler you can prepare yourself for the future by using c++'s pseudo random number faculties:

如果您有 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);

That might be slightly easier to grasp, being you don't have to do anything involving modulos and crap... although it requires more code, it's always nice to know some new C++ stuff...

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

Hope this helps - Luke

希望这会有所帮助 - 卢克

回答by Darius Makaitis

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