我如何得到十进制数的结果在除法? C ++,Pi [英] How can I get the result with decimal number in division? C++, Pi
问题描述
我的学校给了我一个计算pi的任务。
My school give me an assignment to calculate 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。
(有些网站告诉我这样做)
也许我错了。
I guess that when I do (4 / denominator), the result will lose the decimal number although I have changed some declarations of data type from int to double. (Some websites tell me to do this.) Maybe I do it wrongly.
如何处理此问题?
以下是我的计划。
#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 / denominator)
表达式导致 int
,因为 negativeController
和分母
int
。换句话说,你在这里做一个整数除法,这解释了为什么你没有得到预期的结果。
The (negativeController * 4 / denominator)
expression results in an int
because both negativeController
and denominator
are int
. In other words, you're doing an integer division here which explains why you don't get the expected result.
声明(或两者)为 double
强制执行浮点除法。
Declare either (or both) of them as double
to force a floating-point division.
这篇关于我如何得到十进制数的结果在除法? C ++,Pi的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!