visual C++Pi近似程序
visual C++ Pi approximation program
我只是在学习C++,所以我已经开始制作一个简单的程序来近似圆周率的值,使用级数: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"answers"迭代"都正确增加),直到这里的这一行:
pi_approximation = pow((sum * 960),(1 / 6)); // solves the equation for pi
由于某种原因,"pi_approximation"保留其值1,因此打印到"cout"的文本为"1"。
问题是整数除法:
(1 / 6)
将返回0。我相信你知道,任何0的幂都是1。
对于浮点除法,请更改为((double)1 / (double)6)
或(1.0 / 6.0)
。
(1 / 6) == 0
,因为它使用整数数学-您可能想要(1.0 / 6.0)
。。。
相关文章:
- Mongodb c++驱动程序:如何查询元素的数组
- C++,系统无法执行指定的程序
- 在C++程序中输入的文本文件将不起作用,除非文本被复制和粘贴
- 在VS代码中交叉编译Windows与Linux上的MinGW的SDL程序
- C++ Windows 驱动程序MSB3030无法复制该文件,因为它找不到
- 重载操作程序时出错>>用于类中的字符串 memebr
- 获取日期异步信号安全吗?如果在信号处理程序中使用,它会导致死锁吗
- 试图在visual studio上用C++创建一个桌面应用程序
- 模板元程序查找相似的连续类型名称
- FFmpeg:制作一个应用程序比直接使用ffmepg更好吗
- 从Raspberry Pi / Linux上的Python脚本运行和停止C++程序
- 为什么我的程序不近似Pi
- Pi计算器程序每次运行时都会给出不同的输出
- QT QThread::is在Pi上运行冻结程序
- 无法从C++应用程序中正确生成Raspberry Pi相机应用程序作为子进程
- 如何在Raspberry pi中使用JNI GPIO原生库编译和运行Java程序
- visual C++Pi近似程序
- Raspberry Pi:访问C/C++程序中的命令行
- Windows 7和c++:用于Raspberry Pi的交叉编译应用程序
- C/C++ 程序在 Raspberry Pi 上无法正常工作