使用 C++ 的 1 到 10 之间的随机数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12580820/
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:24:13  来源:igfitidea点击:

Random number between 1 to 10 using C++

c++random

提问by rajat

This code is supposed to generate random number between 1 to 10, but it returns 1 every time.

此代码应该生成 1 到 10 之间的随机数,但每次都返回 1。

int random_integer;
int lowest=1, highest=10;
int range=(highest-lowest)+1;
random_integer = lowest + int(range*rand()/(RAND_MAX + 1.0));
cout << random_integer << endl;

What's wrong in the code?

代码有什么问题?

回答by Luchian Grigore

You're subject to overflow here - range*rand().

您在这里可能会溢出 - range*rand()

Just use what regular folks use: rand() % 10 + 1.

只需使用普通人使用的东西:rand() % 10 + 1.

回答by Fred Foo

range * rand() / (RAND_MAX + 1.0)

does not do what you think. Introduce some parens:

不做你想的。介绍一些括号:

range * (rand() / (RAND_MAX + 1.0))

(Note that this method gives skewed distributions, though.)

(但请注意,此方法会产生偏态分布。)

回答by Anton Guryanov

If you want a random integer between lowestand highest, you'd better write

如果你想要一个lowest和之间的随机整数highest,你最好写

random_integer = lowest + rand() % range

回答by birubisht

I agree with all the solution provided above .
now to get a different sequence every time you run your program you can use srand()function it will provide a seed to rand()function as follows:-

我同意上面提供的所有解决方案。
现在要在每次运行程序时获得不同的序列,您可以使用srand()函数,它将为rand()函数提供一个种子, 如下所示:-

srand(time(NULL))  
random_integer = lowest + rand() % range 

回答by SteveL

This two are always part of my programs

这两个永远是我程序的一部分

float randf(float lo, float hi) {
    float random = ((float) rand()) / (float) RAND_MAX;
    float diff = hi - lo;
    float r = random * diff;
    return lo + r;
}
int randi(int lo, int hi)
{
    int n = hi - lo + 1;
    int i = rand() % n;
    if (i < 0) i = -i;
    return lo + i;
}

回答by Sebastian Mach

You seem to assume that rand()returns a value between 0 and 1.

您似乎假设rand()返回一个介于 0 和 1 之间的值。

This is not correct, it return value between 0 and RAND_MAX.

这是不正确的,它返回 0 到 之间的值RAND_MAX