1

私はちょうど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」です。

4

2 に答える 2

7

問題は整数除算です。

(1 / 6)0 を返します。ご存じのとおり、0 の累乗はすべて 1 です。

浮動小数点除算の場合は、 または に変更し((double)1 / (double)6)ます(1.0 / 6.0)

于 2012-08-20T15:47:51.963 に答える
4

(1 / 6) == 0整数演算を使用しているため-おそらく必要です(1.0 / 6.0)...

于 2012-08-20T15:49:29.670 に答える