题目链接:7-15 计算圆周率
一. 题目
1. 题目
2. 输入输出样例
3. 限制
二、代码
1. 代码实现
#include <stdio.h>
// 分子:阶乘
static unsigned long long int JieCheng (unsigned int n) {
if (n == 1) {
return 1;
} else {
return n * JieCheng(n - 1);
}
}
// 分母:等差数列乘积,(2*0+1)*...* (2*n+1)
static unsigned long long int TwoNAdd1 (unsigned int n) {
if (n == 1) {
return 3;
} else {
return (2 * n + 1) * TwoNAdd1(n - 1);
}
}
static float lastValue (unsigned int n) {
return JieCheng(n) * 1.0 / TwoNAdd1(n);
}
int main(void) {
unsigned int n;
float limit, temp, result;
if (scanf("%f", &limit) != 1) {
return -1;
}
n = 1;
temp = 1;
result = 2;
while (temp > limit) {
temp = lastValue(n++);
result += temp * 2;
}
printf("%.6f\n", result);
return 0;
}
2. 提交结果
三、代码优化
1. 代码实现
#include <stdio.h>
// 分子:阶乘
static unsigned long long int JieCheng (unsigned int n) {
unsigned int chengShu;
if (n % 2) {
chengShu = 1;
} else {
chengShu = n;
}
if (n == 1) {
return 1;
} else {
return chengShu * JieCheng(n - 1);
}
}
unsigned int N;
// 分母:等差数列乘积,(2*0+1)*...* (2*n+1)
static unsigned long long int TwoNAdd1 (unsigned int n) {
unsigned int chengShu;
chengShu = 2 * n + 1;
if (chengShu <= N) { // 小于N的项,均存在分子中,约掉
return 1;
}
if (n == 1) {
return chengShu;
} else {
return chengShu * TwoNAdd1(n - 1);
}
}
static float lastValue (unsigned int n) {
return JieCheng(n) * 1.0 / TwoNAdd1(n);
}
int main(void) {
float limit, temp, result;
if (scanf("%f", &limit) != 1) {
return -1;
}
N = 1;
temp = 1;
result = 2;
while (temp > limit) { // 精度判断
temp = lastValue(N);
N++;
result += temp * 2;
}
printf("%.6f\n", result);
return 0;
}