C++ Pi近似程序

use*_*083 1 c++ pi visual-c++

我只是在学习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
    }
}
Run Code Online (Sandbox Code Playgroud)

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

pi_approximation = pow((sum * 960),(1 / 6)); // solves the equation for pi
Run Code Online (Sandbox Code Playgroud)

由于某种原因,'pi_approximation'保留其值为1,因此打印到'cout'的文本为"1".

Chr*_*gis 7

问题是整数除法:

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

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