[英]Adding random integer number in c++
如何在C ++中將100到-100之間的隨機整數添加到int變量?
value += (rand() % 201) - 100; // it's 201 becouse with 200 the value would be in [-100, 99]
不要忘記初始化隨機值的種子(調用srand()),否則它將生成相同的值。 初始化種子的一種好方法是使用時間:
srand(time(NULL));
int rnd = 0;
rnd += ( ( rand() * 200 ) / RAND_MAX ) - 100;
編輯:顯然,這將有RAND_MAX等於INT_MAX的問題。 在這種情況下,下面的答案是: 在c ++中添加隨機整數可能更合適。
編輯:在Windows平台上,RAND_MAX定義為0x7fff,因此此計算將成功。 在其他平台上可能並非如此。
您可以這樣做:
生成一個0到100之間的隨機數,並用0到100之間的隨機數減去它。
#include <cstdlib>
#include <ctime>
#include <iostream>
using namespace std;
int main()
{
srand((unsigned)time(0));
int random_integer;
random_integer = (rand()%101) - (rand()%101);
cout << random_integer << endl;
return 0;
}
在C ++ 11中:
#include <random>
int main()
{
typedef std::mt19937_64 G;
G g;
typedef std::uniform_int_distribution<> D;
D d(-100, 100);
int x = 0;
x += d(g);
}
其他隨機性來源也可以使用,例如:
minstd_rand0
minstd_rand
mt19937
ranlux24_base
ranlux48_base
ranlux24
ranlux48
knuth_b
只需更改typedef G
以適合您的口味即可。 您可以在構建時隨意添加g
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.