c语言 求π的近似值

               

用公式π/4=1-1/3+1/5-1/7...求π的近似值,直到发现某一项的绝对值小于10^6为止(该项不累加)

解:程序:

#include<stdio.h>

#include<math.h>

int main()

{

 int sign = 1;

 double pi = 0.0, n = 1.0, term = 1.0;//term表示当前项

 while (fabs(term) >= 1e-6)

 {

  pi += term;

  n += 2;

  sign = -sign;

  term = sign / n;

 }

 pi *= 4;

 printf("pi=%10.8f\n", pi);

 return 0;

}

结果:

pi=3.14159065

请按任意键继续. . .

本程序输出的结果是pi=3.14159065,虽然输出了8位小数,但是只有前5位小数3,14159是准确的,因为第7位已经小于10^-6,后面的项没有累加。

再看如下两个精度不同的程序:

程序1:

#include<stdio.h>

#include<math.h>

int main()

{

 int sign=1;

 int count = 0;

 double pi = 0.0, n = 1.0, term = 1.0;//term表示当前项

 while(fabs(term)>=1e-6)

 {

  count++;

  pi += term;

  n += 2;

  sign = -sign;

  term = sign / n;

 }

 pi *= 4;

 printf("pi=%10.8f\n",pi);

 printf("count=%d\n",count);

 return 0;

}

结果:

pi=3.14159065

count=500000

请按任意键继续. . .

程序2:

#include<stdio.h>

#include<math.h>

int main()

{

 int sign=1;

 int count = 0;

 double pi = 0.0, n = 1.0, term = 1.0;//term表示当前项

 while(fabs(term)>=1e-8)//变化部分

 {

  count++;

  pi += term;

  n += 2;

  sign = -sign;

  term = sign / n;

 }

 pi *= 4;

 printf("pi=%10.8f\n",pi);

 printf("count=%d\n",count);

 return 0;

}

结果:

pi=3.14159263

count=50000000

请按任意键继续. . .

精度不同,运行时间不同,程序2精度更高,但是运行次数是程序1的100倍。


本文出自 “岩枭” 博客,请务必保留此出处http://yaoyaolx.blog.51cto.com/10732111/1741580

           

再分享一下我老师大神的人工智能教程吧。零基础!通俗易懂!风趣幽默!还带黄段子!希望你也加入到我们人工智能的队伍中来!https://blog.csdn.net/jiangjunshow

猜你喜欢

转载自blog.csdn.net/qq_43667626/article/details/86158745
今日推荐