First attach this one source, this is my learning C language often encountered a small problem.
// 用pi4≈1-1/3+1/5-1/7+...公式求pi的近似值,
// 直到某一项的绝对值小于10的-6次方为止。
#include<stdio.h>
#include<math.h>
int main(){
int i,sign=-1;
float temp=1, pi=0;
//for(i=3;fabs(temp)>=1e-6;i+=2)
i=3;
while(fabs(temp)>=1e-6){
pi=pi+temp;
temp=sign*(1.0/i);
sign=-1.0*sign;
i+=2;
}
pi*=4;
printf("%f",pi);
return 0;
}
In the code segment, since the float temp = 1, pi = 0; for the single precision floating point data type, the multiplication and division in doing so problems will force the format conversion will occur, so in order to avoid this problem, 1.0 multiplied by a calculation in the previous conversion code format, has been defined as the present int i, sign = -1 integer data to floating point conversion.