C++ srand() 不工作

c++ srand() not working

没看懂大家说的: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<<"n= "<<n<<endl;

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

解决方案
n= rand()%10+1;

后打印

srand(int) 抖动数取决于参数传递的值。如果您给出相同的数字,则随机数将相同。 在您的 URL 中,人们调用了 srand(time(NULL)) 两次,但计算机的时钟没有时间在两次调用之间切换。所以随机数是一样的