我正在尝试为近似的算法编写C代码。它应该得到一个立方体的体积和那个立方体内部的球体的体积(球体的半径是立方体的侧面的1/2)。然后我应该将立方体的体积除以球体的体积,然后乘以6得到pi。它正在工作,但是在应该获得体积的部分中却做得很奇怪。我认为这与我为近似值选择的增量有关。如果使用方4的立方体,而不是给我64的体积,那么它给我6400。使用球体而不是33,则给我3334。
有人可以找出答案吗?这是代码(我评论了相关部分):
#include <stdio.h>
int in_esfera(double x, double y, double z, double r_esfera){
double dist = (x-r_esfera)*(x-r_esfera) + (y-r_esfera)*(y-r_esfera) + (z-r_esfera)*(z-r_esfera);
return dist <= (r_esfera)*(r_esfera) ? 1 : 0;
}
double get_pi(double l_cubo){
double r_esfera = l_cubo/2;
double total = 0;
double esfera = 0;
//this is delta, for the precision. If I set it to 1E anything less than -1 the program continues endlessly. Is this normal?
double delta = (1E-1);
for(double x = 0; x < l_cubo; x+=delta){
printf("x => %f; delta => %.6f\n",x,delta);
for(double y = 0; y <l_cubo; y+=delta){
printf("y => %f; delta => %.6f\n",y,delta);
for(double z = 0; z < l_cubo; z+=delta){
printf("z => %f; delta => %.6f\n",z,delta);
total+=delta;
if(in_esfera(x,y,z,r_esfera))
esfera+=delta;
}
}
}
//attempt at fixing this
//esfera/=delta;
//total/=delta;
//
//This printf displays the volumes. Notice how the place of the point is off. If delta isn't a power of 10 the values are completely wrong.
printf("v_sphere = %.8f; v_cube = %.8f\n",esfera,total);
return (esfera)/(total)*6;
}
void teste_pi(){
double l_cubo = 4;
double pi = get_pi(l_cubo);
printf("%.8f\n",pi);
}
int main(){
teste_pi();
}
我正在尝试为近似pi的算法编写C代码。应该获得一个立方体的体积和该立方体内部的球体的体积(球体的半径是立方体的半径的1/2 ...
a * b * c
这样的乘法在整数上
total+=delta;
if(in_esfera(x,y,z,r_esfera))
esfera+=delta;