首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C语言 >

一个关于c语言随机函数的有关问题

2012-10-07 
一个关于c语言随机函数的问题#include stdio.h#includetime.h#includestdlib.h#define N 40000void

一个关于c语言随机函数的问题
#include "stdio.h"
#include"time.h"
#include"stdlib.h"
#define N 40000
void main() //为什么π定了?
{ int rand(void);
int count=0,c=0;
int x,y;float a;
  srand((int)time(0));
 while(c++<=N)
 { x=rand()%101;
 y=rand()%101;
  if(x*x+y*y<=10000)
  count++;
 }
printf("%d\n",count);
a=4*count/N;
printf("%lf",a);
}为什么最后N的值在变,而a一直都是3.0000?

[解决办法]

C/C++ code
#include "stdio.h"#include"time.h"#include"stdlib.h"#define N 4000000void main() //为什么π定了?{ int rand(void);int count=0,c=0;int x,y;float a;srand((int)time(0));while(c++<=N){ x=rand()%101;y=rand()%101;if(x*x+y*y<=10000)count++;}printf("%d\n",count);a=4.0*count/N;printf("%lf\n",a);}
[解决办法]
C/C++ code
#include "stdio.h"#include"time.h"#include"stdlib.h"#define N 40000void main() //为什么π定了?{ int rand(void);//这行多余了,因为stdlib.h中已经声明过了int count=0,c=0;int x,y;float a;  srand((int)time(0)); while(c++<=N) { x=rand()%101;  y=rand()%101;  if(x*x+y*y<=10000)  count++; }printf("%d\n",count);a=4*count/N;// 这一行有问题,你的4  count N都是整数,所经右边的结果也是整数,因为N足够在,所以通常是3//3 传给float,就是3.0000了// a = 4*count/(double)N;//这样写就可以了.printf("%lf",a);} 

热点排行