我的上一篇博客提出了“c语言—srand(time(NULL))产生的随机数一样”的问题,并且分析了产生这样的问题的原因,现在给大家讲解这种问题的处理方法,先直接上代码给大家看效果。
#include<stdio.h>
#include<stdlib.h> //提供srand() rand()
#include<math.h> //提供round() pow()
#include<time.h> //提供time(NULL)
#include<windows.h>//提供Sleep()
void round2(); //除法:四舍五入保留整数位
void round3(); //除法:c语言中round函数的用法 round函数只有一个参数 有两个参数的不是c语言
int main()
{
round2();
Sleep(1000);
round3();
return 0;
}
void round2()
{
int a,b;
int c;
srand(time(NULL));
a=rand()%100-50;
b=rand()%100+1;
if(a>=0)
{
c=(a+b/2)/b;
}
else
{
c=(a-b/2)/ b;
}
printf("\n%d/%d=%d\n",a,b,c);
}
void round3()
{
int a,b;
double c;
srand(time(NULL));
a=rand()%100-50;
b=rand()%100+1;
c=round((double)a/b);
printf("\n%d/%d=%.0lf\n",a,b,c);
}
测试结果:
15/62=0
18/10=2
Process returned 0 (0x0) execution time : 3.835 s
Press any key to continue.
大家可以看到上述产生的随机数不一样了。
上一篇博客中讲述了产生的随机数一样的原因是程序是在1s内完成的,所以这里可以让程序执行的时间大于1s。
这里我使用的是Sleep()函数。
在使用Sleep()函数时有三个注意事项:
1.头文件<windows.h>
2.Sleep()的S要大写
3.Sleep(1000)是程序睡眠1s(即1000是1s)