【问题标题】:c++ srand() not working [closed]c ++ srand()不工作[关闭]
【发布时间】:2016-05-09 10:20:00
【问题描述】:

没看懂大家在这里说什么:srand(time(NULL)) doesn't change seed value quick enough 我应该每次都使用 srand() 生成不同的随机数,但我一直得到相同的数字,有什么建议吗?

#include <iostream>
 #include <time.h>
using namespace std;

int main()
{
    int n, num;
    cout<<"Enter the number:\n";
    cout<<"n= "<<n<<endl;
    cin>>num;
     srand(time(NULL));
    n= rand()%10+1;

    if(n==num)
        cout<<"win\n";
    else
        cout<<"lose\n";


    return 0;
}

【问题讨论】:

  • 你每次得到多少号码?
  • cout&lt;&lt;"n= "&lt;&lt;n&lt;&lt;endl;n 初始化之前完成。
  • 我每次都得到 0
  • @Amal - 你怎么知道的?在n= rand()%10+1; 之后添加一个print of n`,而不是像现在这样。
  • 如果这解决了你的问题,你应该接受@MohitJain 的回答,这样人们就可以看到问题已经解决了:-)

标签: c++ srand


【解决方案1】:
cout<<"n= "<<n<<endl;

您在初始化之前打印n,显示undefined behavior

解决方案
n= rand()%10+1;之后打印

【讨论】:

    【解决方案2】:

    srand(int) 摇动数字取决于参数传递的值。如果你给出相同的数字,随机数将是相同的。 在您的 URL 中,人们拨打了两次 srand(time(NULL)),但计算机的时钟没有时间在两次呼叫之间更改。所以随机数是一样的。

    【讨论】:

      猜你喜欢
      • 2017-07-06
      • 1970-01-01
      • 2015-04-15
      • 1970-01-01
      • 1970-01-01
      • 2016-03-02
      • 2016-04-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多