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

Jam*_*min 19 c++

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

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

    #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;

    }
Run Code Online (Sandbox Code Playgroud)

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

如果答案非常简单,请原谅我,我是一个菜鸟程序员.的xD

Sid*_*gal 46

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

int randNum = rand()%(max-min + 1) + min;
Run Code Online (Sandbox Code Playgroud)

(包括最大和最小)

  • 对于大多数用途,这个答案可能已经足够好了,但OP应该知道,如果`rand()`的范围不能被`max - min + 1整除,那么这种方法对低端有一点偏差. . (4认同)
  • `rand`返回'0`和`RAND_MAX`之间的数字.这是模数的"RAND_MAX + 1"可能输入值.有'max - min + 1`可能的输出值.如果输入与输出的比率不是整数,那么您最终会对较低的数字产生较小的偏差.想象一下,写出所有`RAND_MAX + 1`输入:`0,1,2,...... RAND_MAX`,对吗?现在在它们下面写出后模数(对于'min = 0`和`max = 5`),说:`0,1,2,3,4,5,0,1,2,3,4, 5,0,1,2,3,4,5`等等.现在,如果`RAND_MAX`不能被'6'整除,你得到一个部分循环'0,1,2'...... (4认同)
  • ......或者像最后一样。这意味着“0、1、2”输出比“3、4、5”输出多——让你的算法偏向于“0、1、2”答案。 (4认同)

Riv*_*asa 33

真的很快,很容易:

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

就是这样.但是,这偏向于低端,但如果你使用的是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);
Run Code Online (Sandbox Code Playgroud)

但你也可以删除普通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;
}
Run Code Online (Sandbox Code Playgroud)

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


小智 19

如果你有一个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);
Run Code Online (Sandbox Code Playgroud)

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

希望这会有所帮助 - 卢克


Dar*_*tis 5

rand() % ((highestNumber - lowestNumber) + 1) + lowestNumber
Run Code Online (Sandbox Code Playgroud)