gpt4 book ai didi

C++ Pi近似程序

转载 作者:塔克拉玛干 更新时间:2023-11-03 08:19:34 26 4
gpt4 key购买 nike

我刚开始学习 C++,所以我开始编写一个简单的程序来近似 pi 的值,使用的数列为:Pi ^ 6/960 = 1 + 1/3 ^ 6 + 1/5 ^ 6。 .. 以此类推,继续计算奇数的分母的 6 次方。这是我的代码:

/*-------------------------------------------
* AUTHOR: *
* PROGRAM NAME: Pi Calculator *
* PROGRAM FUNCTION: Uses an iterative *
* process to calculate pi to 16 *
* decimal places *
*------------------------------------------*/
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
double pi_approximation = 0; // the approximated value of pi
double iteration = 3; // number used that increases to increase accuracy
double sum = 1; // the cumulative temporary total

int main ()
{
while (true) // endlessly loops
{
sum = sum + pow(iteration,-6); // does the next step in the series
iteration = iteration + 2; // increments iteration
pi_approximation = pow((sum * 960),(1 / 6)); // solves the equation for pi
cout << setprecision (20) << pi_approximation << "\n"; // prints pi to maximum precision permitted with a double
}
}

代码似乎工作正常(变量“sum”和“iteration”都正确增加)直到这里的这一行:

pi_approximation = pow((sum * 960),(1 / 6)); // solves the equation for pi

由于某种原因,“pi_approximation”保留其值 1,因此打印到“cout”的文本为“1”。

最佳答案

问题是整数除法:

(1/6) 将返回 0。我相信您知道,任何 0 的幂都是 1。

对于浮点除法,更改为 ((double)1/(double)6)(1.0/6.0)

关于C++ Pi近似程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12040851/

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