在C++中生成随机整数

3

我刚刚在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

2
在程序开头,您必须初始化随机数生成器。包含cstdlib头文件并在主函数开头添加srand(time(0)); - Abhishek Bansal
@AbhishekBansal +1,尝试使用srand(time(0)); - Jossef Harush Kadouri
@JossefHarush 编辑过。 - Abhishek Bansal
1
请仅返回翻译后的文本:以及这个:https://dev59.com/PHNA5IYBdhLWcg3wSrqa - Richard Hodges
这里有一个答案:http://stackoverflow.com/a/21724736/2567683 - Nikos Athanasiou
3个回答

12

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

2
如果你只使用std命名空间的一小部分,那么导入整个std命名空间并不总是一个好主意。这只是我的个人意见。 - Iosif Murariu
@IosifM。没错。我本来以为我可以糊弄过去,因为只是在一个函数和代码示例中,但当然应该正确地处理它。我已经修复了它。 - nwp
请使用C++11版本,不要传播rand()混乱的代码。 - dutt
@nwp:并不是要成为一个代码纳粹,只是想让原帖作者记住这一点。无论如何,像dutt说的那样,干得好。 - Iosif Murariu

0

你需要使用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;
}

结果存在偏差。 - alecail

0

试试这个:

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

这也适用于您的随机数。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接