gpt4 book ai didi

c++ - 找到第 N 位的 Pi

转载 作者:太空宇宙 更新时间:2023-11-04 14:35:34 26 4
gpt4 key购买 nike

我开始自学 C++,直到秋季开课。我想知道您是否可以帮助我想出一个更好的方法来询问用户他们想要的数字 pi 的位数,然后显示它。我的问题是使用 pi = atan(1)*4 不精确到小数点后 10 位左右。是否有更好的内置数字,圆周率至少有 20 位小数?这是我目前所拥有的,谢谢!

#include <iostream>
#include <string>
#include <iomanip>
#include <ios>
#include <sstream>
using namespace std;
using std::setprecision;
using std::streamsize;


int main()
{
double pi = atan(1)*4;
int input = 0;
while(true)
{
cout << "Please enter how many digits of PI you would like to see (Max 20): ";
cin >> input;
if(input > 0 && input <= 20)
{
break;
}
else
{
cout << "That's not a valid number! Try again." << endl;
}
}
streamsize prec = cout.precision();
cout << setprecision(input);
cout << "Here you go: " << pi <<endl;
system("pause");
}

最佳答案

执行此操作的最简单方法可能只是有一个包含所需数字的 std::string ("3.14159265358979323846264338327950288419"),然后只打印第一个输入小数点后的数字。

关于c++ - 找到第 N 位的 Pi,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17559286/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com