问题:# 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);}怎么不对呢?谢谢!这个问题有好的意见或
建议,请留言
|