您当前的位置: 百科371电脑/网络C/C++ → 电脑/网络内容 退出登录 用户管理 用户注册
本类热门文章
相关文章
中原建材网
随机函数计算圆周率的值

减小字体 增大字体

问题:# include <stdio.h># include <stdlib.h># include <time.h>main(){ int count=0,i,j; for(int c = 1; c <= 100; c++) { srand(c); i=(float)rand()/32767.0; j=(float)rand()/32767.0; if (i*i + j*j <= 1) { count++; } } printf(%d pi = %f,count,count/100.0*4);}怎么不对呢?谢谢!  

//可以改成以下形式,count的值越大,算出的圆周率越精确,OK?
//另,这个算法是面积比,你除的32767.0是什么意义呢?除以rand()的最大值即可
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
int count = 100;
int inner = 0;
double x = 0.0;
double y = 0.0;

srand(time(0));
for (int i=0; i<count; i++)
{
x = (double)rand()/RAND_MAX;
y = (double)rand()/RAND_MAX;
if (x*x + y*y <= 1)
{
inner++;
}
}
printf("%d pi = %f", inner, (double)inner/count*4);
}

如果你对# include <stdio.h># include <stdlib.h># include <time.h>main(){ int count=0,i,j; for(int c = 1; c <= 100; c++) { srand(c); i=(float)rand()/32767.0; j=(float)rand()/32767.0; if (i*i + j*j <= 1) { count++; } } printf(%d pi = %f,count,count/100.0*4);}怎么不对呢?谢谢!这个问题有好的意见或 建议,请留言
[] [返回上一页] [打 印]
电脑/网络评论 (评论内容只代表网友观点,与本站立场无关!)

用户名: 查看更多评论

分 值:100分 85分 70分 55分 40分 25分 10分 0分

内 容:

         (注“”为必填内容。) 验证码: 验证码,看不清楚?请点击刷新验证码

中原建材网 简单版 站长QQ:382546553