Zhejiang PTA <Title Set basic programming>: calculate pi 7-15
Title Description
The following relationship, pi evaluated, until a final value of less than a given threshold.
Input format
input is less than a given threshold in a row.
Output format
in the output line satisfies approximate pi threshold condition is output to six decimal places.
SAMPLE INPUT
0.01
Sample Output
3.132157
A Code: C language
first, I was with two functions (see below), a molecule, a denominator, and then divide the two functions to solve. However, direct calculation of n! Will long integer, not desirable.
#include "stdio.h"
int f1(int n)
{
int num = 1;
int i;
for (i=1; i<=n; i++){
num *= i;
}
return num;
}
int f2(int n)
{
int num = 1;
int i;
for (i=1; i <= 2*n+1; i++){
if (i%2 == 1) num *= i;
}
return num;
}
int main(){
float sum=1.00;
//scanf("%f",&x);
float x = 0.01;
int i;
for(i=1; ; i++){
float a = f1(i), b = f2(i);
double c;
c = a/b;
if(c >= x) sum += c;
else break;
}
printf("%f",sum*2);
return 0;
}
The results are:
3.121501
Therefore, we should look at the entire fraction as a whole, as follows
#include "stdio.h"
int main(){
int n=1;//第n项
float x, num, sum=1;//x是阈值,num是每一个单项
scanf("%f",&x);
for(num=1; num>=x; n++){
num = num*n/(2*n+1);//每一项都是前一项*n/(2n+1)
sum+=num;
}
printf("%f",sum*2);
return 0;
}
Direct viewed as a whole wording is very simple and correct.
Code two: Python
same lines, with python and very fast
# -*- coding: utf-8 -*-
x = eval(input())
n = 1
sum0 = 1
num = 1
while num >= x:
num = num*n/(2*n+1)
sum0 = sum0+num
n = n+1
print("{:.6f}".format(sum0*2))