Zhejiang PTA basic programming Title Set: calculate pi 7-15

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.
π 2 = 1 + 1 3 + 2 ! 3 × 5 + 3 ! 3 × 5 × 7 + + n ! 3 × 5 × 7 × × ( 2 n + 1 ) + \frac{\pi}{2}=1+\frac13+\frac{2!}{3\times 5}+\frac{3!}{3\times 5\times7}+\dots+\frac{n!}{3\times 5\times7\times \dots\times(2n+1)}+\dots
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))
发布了16 篇原创文章 · 获赞 0 · 访问量 125

Guess you like

Origin blog.csdn.net/niexinyu0026/article/details/104184715