PAT基础编程题目-7-15 计算圆周率
PAT基础编程题目-7-15 计算圆周率
题目详情
解答
C语言版
#include<stdio.h>
int main() {
float threshold, pi = 1, end =1;
double numerator = 1, denominator = 1; //分子,分母 长整型会溢出
scanf("%f", &threshold);
for (int i = 1; end >= threshold; i++)
{
numerator = numerator * i;
denominator = denominator * (2 * i + 1);
end = numerator / (denominator * 1.0);
pi = pi + end;
}
printf("%.6f", pi * 2);
return 0;
}
C++版
#include<iostream>
#include<iomanip>
using namespace std;
int main() {
float threshold, pi = 1, end = 1;
double numerator = 1, denominator = 1; //分子,分母 长整型会溢出
cin >> threshold;
for (int i = 1; end >= threshold; i++)
{
numerator = numerator * i;
denominator = denominator * (2 * i + 1);
end = numerator / (denominator * 1.0);
pi = pi + end;
}
cout << fixed << setprecision(6) << pi * 2;
return 0;
}
Java版
import java.text.DecimalFormat;
import java.util.Scanner;
public class Main{
public static void main(String[] args) {
float threshold = 0, pi = 1, end = 1;
double numerator = 1, denominator = 1; //分子,分母 长整型会溢出
Scanner scanner = new Scanner(System.in);
if (scanner.hasNext()) {
threshold = scanner.nextFloat();
}
scanner.close();
for (int i = 1; end >= threshold; i++)
{
numerator = numerator * i;
denominator = denominator * (2 * i + 1);
end = (float) (numerator / (denominator * 1.0));
pi = pi + end;
}
DecimalFormat decimalFormat = new DecimalFormat("#.000000");
System.out.println(decimalFormat.format(pi*2));
}
}
创作不易,喜欢的话加个关注点个赞,谢谢谢谢谢谢!