代码如下:
//圆周率 π = 4∑(k=0,..∞)(-1)^k/(2k+1)
//π = 3.14159265358979323846
public class yzq {
public static void main(String[] args) {
// TODO Auto-generated method
stub
int n=0;
double a=0;
for (n=0;n<=10000000;n++ )
{
a = a + 4*Math.pow(-1,n)/(2*n+1);
System.out.println("第 "+n+"
位
"+a);
}
System.out.println("最后一位
"+a);
}
}
//程序运行结果
//第10
次计算
3.232315809405594
//第100
次计算
3.1514934010709914
//第1000
次计算
3.1425916543395442
//第10,000
次计算
3.1416926435905346
//第100,000
次计算
3.1416026534897203
//第1000,000
次计算
3.1415936535887745
//第10,000,000次计算
3.1415927535897814
//第100,000,000次计算
3.141592643589326
//第999,999,990次计算
3.1415926545880506
//第999,999,991次计算
3.1415926525880504
//第999,999,992次计算
3.1415926545880506
//第999,999,993次计算
3.1415926525880504
//第999,999,994次计算
3.1415926545880506
//第999,999,995次计算
3.1415926525880504
//第999,999,996次计算
3.1415926545880506
//第999,999,997次计算
3.1415926525880504
//第999,999,998次计算
3.1415926545880506
//第999,999,999次计算
3.1415926525880504
//第1,000,000,000次计算
3.1415926545880506
下面是C语言写的一个计算圆周率的方法,你参考一下(其中cout是用来输出的):
/*
计算π值的公式为:
π = 2 + 2/3 + 2/3*2/5 + 2/3*2/5*3/7 + ...
*/
//求PAI小数点后DISPCNT位
void pai()
{
int i = 0;
const ARRSIZE=2010, DISPCNT=2000;
char x[ARRSIZE], z[ARRSIZE];
int a=1, b=3, c, d, Run=1, Cnt=0;
for (i = 0; i < ARRSIZE; i ++)
{
x[i] = 0;
z[i] = 0;
}
x[1] = 2;
z[1] = 2;
while(Run && (++Cnt<200000000))
{
d = 0;
for(i=ARRSIZE-1; i>0; i--)
{
c = z[i]*a + d;
z[i] = c % 10;
d = c / 10;
}
d = 0;
for(i=0; i
c = z[i]+d*10;
z[i] = c / b;
d = c % b;
}
Run = 0;
for(i=ARRSIZE-1; i>0; i--)
{
c = x[i] + z[i];
x[i] = c%10;
x[i-1] += c/10;
Run |= z[i];
}
a++;
b+=2;
}
cout<<(int)x[1]<<".";
for(i=0; i
if(i && (i%76==0))
cout<<"\n";
cout<<(int)x[i+2];
}
cout<<"\n";
}
public class Test {
public static void main(String args[]) {
long time = System.currentTimeMillis();
Pi pi = new Pi(200000000);
pi.comput();
System.out.println(pi.getPi());
System.out.println("消耗时间>>" + (System.currentTimeMillis() - time));
}
}
class Pi {
private double pi;
private int count;
public Pi() {
}
public Pi(int count) {
this.count = count;
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
public double getPi() {
return pi;
}
public void comput() {
pi = 1;
int max = count * 2 + 1;
for (int i = 3; i <= max; i = i + 4) {
pi -= 1d / i;
}
for (int i = 5; i <= max; i = i + 4) {
pi += 1d / i;
}
pi *= 4;
}
}
你想干嘛?