用C语言求圆周率,要求用到for循环。

我说的是用C语言来求,而不是用C++

【C++编译器中的运算程序】
微机WindowsXP中Dev-cpp中的运算程序(30000位)(C++)
#include <cstdlib>
#include <iostream>
#include <fstream>
#define N 30015
using namespace std;
void mult (int *a,int b,int *s)
{
for (int i=N,c=0;i>=0;i--)
{
int y=(*(a+i))*b+c;
c=y/10;
*(s+i)=y%10;
}
}
void divi (int *a,int b,int *s)
{
for (int i=0,c=0;i<=N;i++)
{
int y=(*(a+i))+c*10;
c=y%b;
*(s+i)=y/b;
}
}
void incr(int *a,int *b,int *s)
{
for (int i=N,c=0;i>=0;i--)
{
int y=(*(a+i))+(*(b+i))+c;
c=y/10;
*(s+i)=y%10;
}
}
bool eqs(int *a,int *b)
{
int i=0;
while (((*(a+i))==(*(b+i)))&&(i<=N)) i++;
return i>N;
}
int main(int argc, char *argv[])
{
cout << "正在计算 . . . (0%)";
int lpi[N+1],lls[N+1],lsl[N+1],lp[N+1];
int *pi=lpi,*ls=lls,*sl=lsl,*p=lp;
for (int i=0;i<=N;i++)*(pi+i)=*(ls+i)=*(sl+i)=*(p+i)=0;
memset(pi,0,sizeof(pi));
memset(ls,0,sizeof(ls));
memset(sl,0,sizeof(sl));
memset(p,0,sizeof(p));
*pi=*ls=*sl=1;
for (int i=1;true;i++)
{
mult(ls,i,sl);
divi(sl,2*i+1,ls);
incr(pi,ls,p);
if (eqs(pi,p))
{
cout << "\b\b\b\b100%)\n";
break;
}
int *t;
t=p;
p=pi;
pi=t;
//if (i%1000==0) cout << i << " ";
if(i%1000 == 0)
{
/*cout << i/1000 << "% ";
if(i%5000 == 0)
cout << endl;*/
if(i/1000 < 11)
{
cout << "\b\b\b";
} else {
cout << "\b\b\b\b";
}
cout << i/1000 << "%)";
}
}
cout << endl;
cout << "计算完成\n正在保存 . . .\n";
mult(p,2,pi);
ofstream fout("pi.txt");
fout << *pi << ".";
for (int i=1;i <= N - 15;i++)
{
fout << *(pi+i);
if (i%10==0) fout << " ";
if (i%80==0) fout << endl;
}
cout << "保存完成\n";
cout<< "按回车键退出";
cin.peek();
return EXIT_SUCCESS;
}
注:①运行时会有数据弹出,这无关紧要,只为了加快了感觉速度;
注:程序中有语法错误。请高人改正。
运行环境 CodeBlocks C++
#include <iostream>
using namespace std;
long long a=1000000, b, c=2800000, d, e, f[2801000], g;
int main()
{
for( ;b-c; ) f[b++] =a/5;
for( ; d=0, g=c*2; c-=14,printf("%.4d",e+d/a),e=d%a)
for(b=c; d+=f[b]*a,f[b] =d%--g,d/=g--,--b; d*=b ) ;
return 0;
}

参考资料:http://baike.baidu.com/view/3287.html?wtp=tt

温馨提示:答案为网友推荐,仅供参考
第1个回答  2010-11-17
要求圆周率必须要知道圆周率的计算公式,我不知道你准备用什么计算公式,所以写不了程序。我个人觉得写一个祖冲之“割圆术”算法公式不错,可以练练C语言的基本功。
第2个回答  2020-12-26

C语言的数组概念的学习,通过for循环输出打印数组

第3个回答  2010-11-16
3.1415926535.........

相关了解……

你可能感兴趣的内容

本站内容来自于网友发表,不代表本站立场,仅表示其个人看法,不对其真实性、正确性、有效性作任何的担保
相关事宜请发邮件给我们
© 非常风气网