我刚刚开始学习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“。
发布于 2012-08-20 23:47:52
问题是整数除法:
(1 / 6)将返回0。我相信你知道,任何0的幂都是1。
对于浮点除法,更改为((double)1 / (double)6)或(1.0 / 6.0)。
发布于 2012-08-20 23:49:30
(1 / 6) == 0,因为它使用整数计算--您可能需要(1.0 / 6.0)...
https://stackoverflow.com/questions/12040851
复制相似问题