随机数srand()和sleep函数的结合使用

1.等待随机数事件后,程序继续执行。

sleep()函数在Linux中的头文件是#include<unistd.h>中

而在window中,头文件在#include<windows.h>中

time()时间函数包含在头文件#include<time.h>中

srand()随机数函数包括在#include<stdlib.h>头文件中

2.ctime()函数和ctime_s()函数之间的区别

ctime_s()函数的使用

time_t current= time(&current);/*获取当前时间*/

char buff[26]; ctime_s(buff, sizeof buff, &current);

printf("当前日期和时间:%s",buff);

ctime()函数的使用

扫描二维码关注公众号,回复: 8498651 查看本文章

time_t timep;

time(&timep);  //获取从1970至今过了多少秒,存入time_t类型的timep

printf("%s", ctime(&timep)); //用ctime将秒数转化成字符串格式,输出:Tue Nov  5 02:52:05 2019

3.Linux系统中应用

#include <iostream>
#include<iomanip>
#include<unistd.h>
#include<stdlib.h>
#include<time.h>
using namespace std;
void PrintFunction()
{
cout << "CodeWorld!"<<endl;
}
int main(void)
{
int count = 10;
int i = 0;
int temp=0;
while (i < count)
{
time_t timep;
time(&timep);  //获取从1970至今过了多少秒,存入time_t类型的timep
printf("%s", ctime(&timep)); //用ctime将秒数转化成字符串格式,输出:Tue Nov  5 02:52:05 2019
PrintFunction();
srand((unsigned)time(NULL));
temp=rand()%11;
 cout<<"生成的随机数为:"<<temp<<endl<<endl;
sleep(temp);
i++;
}
return 0;
}

 4.在window系统中的应用

#include"stdafx.h"
#include <iostream>
#include<iomanip>
//#include<unistd.h>
#include<windows.h>
#include<stdlib.h>
#include<time.h>
using namespace std;
void PrintFunction()
{
time_t timep=time(&timep);  //获取从1970至今过了多少秒,存入time_t类型的timep
char buff[36];
ctime_s(buff, sizeof(buff), &timep);
printf("%s",buff); //用ctime将秒数转化成字符串格式,输出:Tue Nov  5 02:52:05 2019
cout << "CodeWorld!" << endl;
}
int main(void)
{
int count = 10;
int i = 0;
int temp = 0;
srand((unsigned)time(NULL));
while (i < count)
{
PrintFunction();
//srand((unsigned)time(NULL));
temp = rand() % 11;
cout << "生成的随机数为:" << temp << endl << endl;
Sleep(temp*1000); 
//sleep(1);
i++;
}
//pause(system);
system("pause");
return 0;
}
结果
测试结果

参考文献:1.https://blog.csdn.net/geter_CS/article/details/86592639

2.https://blog.csdn.net/jieyannn/article/details/100769591 

发布了81 篇原创文章 · 获赞 17 · 访问量 6045

猜你喜欢

转载自blog.csdn.net/hopegrace/article/details/102916787