c++中的随机整型

Random int in C++

本文关键字:整型 随机 c++      更新时间:2023-10-16

我刚刚用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;
}

截图:http://tinyurl.com/n49hn3j

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);
}

您需要使用srand函数初始化(种子)随机。更多信息

#include <iostream>
#include <stdlib.h>     /* srand, rand */
#include <time.h>       /* time */
using namespace std;
int main() {
    // Seed the random number generator
    srand(time(0));
    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;
}

试试这个:

#include <ctime>  //for current time 
#include <cstdlib> //for srand
    srand (unsigned(time(0))); //use this seed

这也将适用于您的随机。