如何获得除法十进制数的结果? Pi

我的学校给我一个作业来计算pi.

结果应为:

Question 4
Accuracy set at : 1000

term               pi
1                  4
100                3.13159
200                3.13659
300                3.13826
400                ...
...                ...

我程序中的结果:

term               pi
1                  4
100                3
200                3
300                3
400                ...
...                ...

我想当我这样做(4 /分母)时,尽管我将某些数据类型的声明从int更改为double,但结果将丢失十进制数.
(某些网站告诉我要这样做.)
也许我做错了.

我该如何解决这个问题?

以下是我的程序.

#include <iostream>
using namespace std;


class Four
{
private:
    int inputedAccuracy;
    double pi;
    int denominator;
    int doneTermCounter;
    double oneTerm;
    int negativeController;

public:
    double question4()
    {
        cout << "Accuracy set at : " ;
        cin >> inputedAccuracy;
        cout << endl;
        pi = 0.0;
        denominator = 1.0;
        doneTermCounter = 0;

        negativeController = 1;
        cout << "Term" << "            " << "pi" << endl;
        cout << "1  " << "             " << "4" << endl;


        for (inputedAccuracy; inputedAccuracy > 0; inputedAccuracy -= 100)
        {
            for (int doneTerm = 0; doneTerm < 100; doneTerm++)
            {
                pi = pi + (negativeController * 4 / denominator);
                negativeController *= -1;
                denominator += 2;
                doneTermCounter++;
            }
            if (doneTermCounter >= 10000)
                cout << doneTermCounter << "             " << pi << endl;
            else
                if (doneTermCounter >= 1000)
                    cout << doneTermCounter << "            " << pi << endl;
                else
                    cout << doneTermCounter << "             " << pi << endl;
        }
        return 0.0;
    }
};

感谢您的关注!

解决方法:

pi = pi + (negativeController * 4 / denominator);

(negativeController * 4 /分母)表达式的结果为int,因为negativeController和分母均为int.换句话说,您在这里进行整数除法,这说明了为什么没有得到预期的结果.

将它们中的一个(或两个)声明为双精度以强制进行浮点除法.

上一篇:c-如何让GCC编译器将变量除法转换为mul(如果更快)


下一篇:在Python中对’int’进行类型转换会产生错误的结果