Rad*_*wan 1 c++ random visual-studio
我只是在C++中编写下面的代码,但我有一个问题:它的随机数始终是相同的.. !! 这是我的代码和截图:
#include <iostream>
using namespace std;
int main() {
cout << "I got a number in my mind... can you guess it?" << endl;
int random;
random = rand() % 20 + 1;
cout << random << endl;
system("pause");
return 0;
}
Run Code Online (Sandbox Code Playgroud)
srand(time(0))
如果你没有在最后一次的同一秒内启动它,它将只生成一个新的随机数.使用rand()%20也存在问题.这样做是正确的:
#include <iostream>
#include <random>
int main(){
std::random_device rd;
std::mt19937 mt(rd());
std::uniform_int_distribution<int> dist(1, 20);
std::cout << dist(mt);
}
Run Code Online (Sandbox Code Playgroud)