PAT基础编程题目-7-15 计算圆周率

PAT基础编程题目-7-15 计算圆周率

题目详情

PAT基础编程题目-7-15 计算圆周率_第1张图片

题目地址:https://pintia.cn/problem-sets/14/problems/795

解答

C语言版

#include
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;
}

PAT基础编程题目-7-15 计算圆周率_第2张图片

C++版

#include
#include
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;
}

PAT基础编程题目-7-15 计算圆周率_第3张图片

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));

	}

}

PAT基础编程题目-7-15 计算圆周率_第4张图片

创作不易,喜欢的话加个关注点个赞,谢谢谢谢谢谢!

你可能感兴趣的:(C,C++,Java,PAT,基础编程题)