代码如下:
//利用 4/π=1-1/3+1/5-1/7+...,编程计算π的近似值,直到最后一项的值小于10-4次方为止 //输出π的值,并统计累加的项数 #
include<stdio.h> #include<math.h> int main() { int i; int count = 0; double sign
= 1; double sum=1.000000,term=1.0; for (i = 3; fabs(term) > 1e-5; i += 2) { sign
= -sign; term = sign / i; sum = sum + term; count++; } printf("π=%f,count=%d",4*
sum,count); }
程序运行结果如下:
---------------------------------------------------------------------------------------------------------------------------------------
------------