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

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

题目详情

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

解答

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

	}

}

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

全部评论

相关推荐

10-25 12:05
已编辑
湖南科技大学 Java
若梦难了:我有你这简历,已经大厂乱杀了
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务