如何在C++中使用rand()函数给变量赋予随系统时间的随机值

比如我需要1~50之间的变化随机值:

#include<iostream>
#includ<cstdlib>
#include<ctime>
int main()
{
    srand((unsigned int)(time(0));
    int i=rand()%50+1;
    std::cout<<i;
}

注意:#includ< cstdlib >你也可以不加,也能识别rand函数。使用srand((unsigned int)(time 0))基于当前时间为随机数生成器确定种子并返回unsigned int型,当然仅用srand(time(0))也是可以的。

猜你喜欢

转载自blog.csdn.net/m0_46606140/article/details/106578026