C ++ Pi近似程序 [英] C++ Pi approximation program

查看:155
本文介绍了C ++ Pi近似程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是学习C ++,所以我已经开始做一个简单的程序来近似pi的价值,使用系列:Pi ^ 6/960 = 1 + 1/3 ^ 6 + 1/5 ^ 6。这是我的代码:

  / *  - ----------------------------------------- 
*作者:*
*程序名称:Pi计算器*
*程序函数:使用迭代*
*过程计算pi到16 *
*小数位*
* --- --------------------------------------- * /
#include< iostream> ;
#include< iomanip>
#include< cmath>
using namespace std;
double pi_approximation = 0; // pi
的近似值double iterative = 3; //用于增加准确性的数字
double sum = 1; //累积临时总计

int main()
{
while(true)//无限循环
{
sum = sum + pow迭代,-6); //在系列中的下一步
iteration = iteration + 2; // increment iteration
pi_approximation = pow((sum * 960),(1/6)); //解方程为pi
cout<< setprecision(20)<< pi_approximation<< \\\
; // print pi to maximum precision allowed with a double
}
}

代码似乎工作正常(变量'sum'和'iteration'正确增加)到这里:

  pi_approximation = pow((sum * 960),(1/6)); //解决pi 

的方程,因为某些原因'pi_approximation'保留其值为1,这样打印到'cout'的文本是1。

解决方案

问题是整数除法:



(1/6)将返回0.我相信你知道,0的幂的任何值为1。 >

对于浮点除法,更改为((double)1 /(double)6) (1.0 / 6.0)


I'm just learning C++ and so I have started to make a simple program to approximate the value of pi, using the series: Pi ^ 6 / 960 = 1 + 1 / 3 ^ 6 + 1 / 5 ^ 6... and so on continuing with denominators of odd numbers to the power of 6. Here is my code:

/*-------------------------------------------
 *  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
    }
}

The code seems to work fine (both the variables 'sum' and 'iteration' increase correctly) up to this line here:

pi_approximation = pow((sum * 960),(1 / 6)); // solves the equation for pi

as for some reason 'pi_approximation' retains its value of 1 and as such the text printed to 'cout' is "1".

解决方案

The problem is integer division:

(1 / 6) will return 0. As I am sure you know, anything to the power of 0 is 1.

For floating point division, change to ((double)1 / (double)6) or (1.0 / 6.0).

这篇关于C ++ Pi近似程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆