我是C ++的新手,而且我无法弄清楚我的问题所在。我试图询问用户他们想要使用Gregory - Leibniz系列找到pi的距离,但每当我输入任何数字时,我总是得到4(循环中的1)。在此先感谢:)
#include <iostream>
#include <cmath>
#include <iomanip>
using namespace std;
int main()
{
double x = 0;
double doubleTerms = 0;
cout << "How many terms of pi do you want?" << endl;
cin >> doubleTerms;
cout << "Thanks the amount of terms you want for pi is: " << doubleTerms << endl;
//n is the value for where each number is
//z is to change the number into a negative
//x is to add up into the total value
for(int n = 0; n < doubleTerms; n++)
{
double z = 1 / (2 * n + 1);
if((n % 2) == 1)
{
z = z * -1;
}
x = (x + z);
}
double finalValue = 4 * x;
cout << "The number is: " << finalValue << endl;
system("pause");
return 0;
}
答案 0 :(得分:3)
1 / (2 * n + 1);
将在整数算术中执行,因此任何小数部分都会被截断。
一种解决方法是改为编写1.0 / (2 * n + 1);
:由于类型提升的规则,该术语将在浮点中进行评估。