【问题标题】:Random int in C++ [duplicate]C ++中的随机int [重复]
【发布时间】:2014-06-28 03:10:14
【问题描述】:

我只是用 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

【问题讨论】:

  • 您必须在程序开始时播种随机数生成器。包括 cstdlib 头文件并添加 srand( time(0) );在 main 函数的开头。
  • @AbhishekBansal +1,试试 srand(time(0));
  • @JossefHarush 已编辑。
  • 答案here

标签: c++ visual-studio random


【解决方案1】:

srand(time(0)) 只会产生一个新的随机数,如果你没有在你上次做的同一秒内启动它。还有issues with using 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);
}

【讨论】:

  • 如果您只使用其中的一小部分,那么导入整个 std namespace 并不总是一个好主意。只是我的 0.02 美元
  • @IosifM。真的。虽然我可以摆脱它,因为它只是在一个函数和一个代码示例中,但它当然应该正确完成。我修好了。
  • +1 用于使用 c++11 版本而不是传播 rand() 的混乱
  • @nwp:并不是要成为代码纳粹,只是想把它扔掉,以便 OP 记住这一点。无论如何,正如杜特所说,gj
【解决方案2】:

您需要使用srand 函数初始化(种子)随机数。 more info

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

【讨论】:

  • 结果有偏差
【解决方案3】:

试试这个:

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

这也适用于您的随机。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-08-01
    • 2013-12-24
    • 2018-07-03
    • 1970-01-01
    • 2011-10-23
    • 2012-05-15
    • 1970-01-01
    • 2021-09-28
    相关资源
    最近更新 更多