用泰勒方法和循环计算圆周率

Calculating Pi with Taylor Method C++ and loop

本文关键字:循环 计算 圆周率 方法      更新时间:2023-10-16

圆周率的近似值可以用下面给出的级数来计算:

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

用这个级数写一个c++程序来计算圆周率的近似值。程序的输入n决定了pi值近似值的项数,并输出近似值。包括一个循环,允许用户对新值n重复这个计算,直到用户说她或他想结束程序。

预期结果是:输入要近似的项数(或0退出):1使用一项的近似值是4.00。输入要近似的项数(或0退出):2用两项近似是2.67。输入要近似的项数(或0退出):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;
}

初始化错误:

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

EDIT如果您想重复计算,通常的做法是提取一个函数(不要将所有内容塞进单个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 2 main函数可以是这样的:

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;
  }
}

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

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