[英]C++ Random number generator: How to make numbers random upon every execution
[英]How to make a decimal random number generator in c++?
我試圖制作一個十進制隨機數生成器,用戶輸入最小值和最大值
我查看了其他問題和答案,但它們要么沒有最小值和最大值,要么不起作用。
#include <iostream>
#include <cstdlib>
using namespace std;
int main(){
int low;
int high;
cout<<"what is the lowest number?";
cin>>low;
cout<<"what is the highest number?";
cin>>high;
high++;
low++;
double random;
srand( unsigned(time(NULL) ));
random=(double)rand()/(RAND_MAX+1)*(high-low)+low;
cout<<random;
}
在我輸入 1(min) 和 10(max) 的參數后,我預計編譯器給出的數字是 1.346,但它是一個隨機的負十進制數
問題是,除非您輸入了low
和high
病態值,否則RAND_MAX + 1
可能會溢出int
類型,因此您的程序的行為是未定義的(環繞到 INT_MIN 是一種常見表現,並且會說明對於你觀察到的)。
但是考慮到使用rand()
解決方案無論如何總會有偏差,請考慮
std::random_device rd;
std::mt19937 eng(rd());
std::uniform_real_distribution<> dist(low, high); // the range - does not include high
並用dist(eng)
畫一個數字。 low
和high
的增量。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.