这是我的资料
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
double pi = 0;
long i;
long n;
cout << "Enter the value of n: ";
cin >> n;
cout << endl;
for (i = 0; i < n; i++)
{
if (i % 2 == 0)
pi = pi + (1 / (2 * i + 1));
else
pi = pi - (1 / (2 * i + 1));
pi = 4 * pi;
}
cout << endl << "pi = " << pi << endl;
return 0;
}
然而,这并没有给予所需的输出。例如,n = 9,pi = 262144。我知道可以将pi存储为常量并以这种方式得到结果,但我想知道使用上面的算法做错了什么。
1条答案
按热度按时间baubqpgj1#
因为
long i;
,对于任何i>0
都是零,当i=0
,对于i=1,9
,你得到pi=1;
,你得到pi = 4*pi;
,这就是为什么你得到262144
,也就是4^8
。你可能需要