#include <sys/time.h>
#include <stdio.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include <inttypes.h>
#include <stdint.h>
#include <limits.h>
#include <unistd.h>
uint_fast32_t static cirnum=0,openwrong=0, readwrong=0,overflow=0,goodnum=0;
uint_fast32_t oldrandom()
{
struct timeval ti;
gettimeofday(&ti,NULL);
uint_fast32_t seeds=ti.tv_usec;
// #srandom(seed);
srandom(seeds);
return random();
}
uint_fast32_t myrandom()
{
uint32_t data;
int fd=open("/dev/urandom",O_RDONLY);
if(fd<0 )
{
data=oldrandom();
openwrong++;
}
else if (read(fd,&data,sizeof(data))<=0)
{
data=oldrandom();
readwrong++;
}
else if(data>SSIZE_MAX||data<0)// 有可能溢出
{
overflow++;
}
else goodnum++;
close(fd);
return data%RAND_MAX;
}
void circum()
{
uint_fast32_t xr=myrandom();
long double xrate=xr*1.0/(RAND_MAX-1);
xrate=xrate*xrate;
uint_fast32_t yr=myrandom();
long double yrate=yr*1.0/(RAND_MAX-1);
yrate=yrate*yrate;
if((xrate+yrate)<=1.0)
cirnum++;
}
int main(int argc, char **argv)
{
uint_fast32_t i,num=1999999;
double pi;
for(i=0;i<num;i++)
circum();
printf("the cirnum=%"PRIuFAST32"\n",cirnum);
pi=(cirnum*1.0/num)*4;
printf("openwrong=%"PRIuFAST32",readwrong=%"PRIuFAST32",overflow=%"PRIuFAST32",goodnum=%"PRIuFAST32"\n",openwrong,readwrong,overflow,goodnum);
printf("the pi almost=%lf\n",pi);
return 0;
}
// 以上代码在 13.2 中是能编译通过并运行的。但是是 42.1 中
/*use@linux-yryd:~/bin> gcc -std=c11 random-pi.c
random-pi.c: In function ‘oldrandom’:
random-pi.c:20:3: warning: implicit declaration of function ‘srandom’ -Wimplicit-function-declaration]
srandom(seeds);
^
random-pi.c:21:3: warning: implicit declaration of function ‘random’ -Wimplicit-function-declaration]
return random();
^
random-pi.c: In function ‘myrandom’:
random-pi.c:43:16: error: ‘SSIZE_MAX’ undeclared (first use in this function)
else if(data>SSIZE_MAX||data<0)// 有可能溢出
^
random-pi.c:43:16: note: each undeclared identifier is reported only once for each function it appears in
suse@linux-yryd:~/bin>
*/
又试了一下,这回不用 -std=c11。编译通过了,这是为什么呢?