【问题标题】:Calculating Pi with Taylor Method C++ and loop用 Taylor 方法 C++ 和循环计算 Pi
【发布时间】:2016-07-05 03:47:08
【问题描述】:

可以使用下面给出的系列来计算 pi 的近似值:

pi = 4 * [ 1 - 1/3 + 1/5 - 1/7 + 1/9 ... + ((-1)^n)/(2n + 1) ]

编写一个 C++ 程序,使用这个数列计算 pi 的近似值。该程序采用输入 n 来确定 pi 值的近似值中的项数并输出近似值。包括一个循环,允许用户对新值 n 重复此计算,直到用户说她或他想要结束程序。

预期结果是: 输入要近似的项数(或零以退出): 1 使用 1 项的近似值为 4.00。 输入要近似的项数(或零以退出): 2 使用 2 项的近似值为 2.67。 输入要近似的项数(或零以退出): 0

我现在可以得到正确的结果,但我不知道如何包含一个允许用户重复计算新值 n 的循环,直到用户说她或他想要结束程序。

#include <stdio.h>
#include <iostream>
#include <cmath>
using namespace std;

int main()
{ int n; double pi, sum; 
do { 
     cout << "Enter the number of terms to approximate (or zero to quit):" << endl;
     cin >> n;

if (n >0)
{

        double sum=1.0;
        int sign=-1;

    for (int i=1; i <=n; i++) {
    sum += sign/(2.0*i+1.0);
        sign=-sign;
    }
        pi=4.0*sum;

    cout.setf(ios::fixed);
    cout.setf(ios::showpoint);
    cout.precision(2);

    cout << "The approximation is " << pi << " using "<< n << " terms" << endl;
}
} while(n>0);



    cout << endl;

   return 0;
}

【问题讨论】:

  • 注意:停止预先声明变量。在使用前/使用时声明它们。你把它混合起来。
  • 也许循环 int i 应该等于 0。for (int i=0; i
  • sum += (double)sign/(2.0*i+1.0);
  • sign *=-1; -> sign=-sign 会更好
  • 你输掉了第一个学期。

标签: c++


【解决方案1】:

你有错误的初始化:

double sum=0.0;
int sign=1;

应该是

double sum = 1.0;
int sign = -1;

循环也错了(有错字?),应该是

for (int i = 1; i < n; i++) { /* please, notice "i < n" and "{"  */
    sum += sign / (2.0 * i + 1.0);
    sign = -sign; /* more readable, IMHO than  sign *=-1; */
}

pi = 4.0 * sum; /* you can well move it out of the loop */

编辑如果你想重复计算一个常见的做法是提取一个函数(不要把所有东西都塞进一个main):

double compute(int n) {
  if (n < 0) 
    return 0.0;

  double sum = 1.0;
  int sign = -1;

  for (int i = 1; i < n; i++) { 
    sum += sign / (2.0 * i + 1.0);
    sign = -sign; /* more readable, IMHO than  sign *=-1; */
  }

  return 4.0 * sum;
}

EDIT 2main 函数可能是这样的:

int main() {
  int n = -1;

  /* quit on zero */
  while (n != 0) {
    cout << "Enter the number of terms to approximate (or zero to quit):" << endl;
    cin >> n;

    if (n > 0)
      cout << "The approximation is " << compute(n) << " using "<< n << " terms" << endl;
  }
}

【讨论】:

  • 当我输入一个时,预期结果应该是 4.00 而不是 2.66667。
  • @ZiWei Pan:然后在循环条件中将i &lt;= n更改为i &lt; n(见我的编辑)
  • @Dmitry Bychenko:谢谢!如何使循环重复计算?
  • @ZiWei Pan:如果你想重复计算,提取一个函数(见我的编辑)
  • @Dmitry Bychenko:我不是很懂你的代码。我已经更新了我的代码和我的问题。我只是不确定如何在我的代码中使用它。
【解决方案2】:

交替符号必须是循环的一部分。使用复合语句将其包含到循环体中:

for (int i=1; i <=n; i++) {
  sum += sign/(2.0*i+1.0);
  sign *=-1;
}

【讨论】:

  • 我已经更新了我的代码。我不知道为什么我的代码不能重复。
猜你喜欢
  • 2015-12-16
  • 1970-01-01
  • 1970-01-01
  • 2017-12-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-21
  • 1970-01-01
相关资源
最近更新 更多