c++ - 使用泰勒方法 C++ 和循环计算 Pi

标签 c++

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

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

用这个数列写一个C++程序来计算圆周率的近似值。该程序采用输入 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;
}

最佳答案

你有错误的初始化:

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

关于c++ - 使用泰勒方法 C++ 和循环计算 Pi,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38163899/

相关文章:

c++ - 防止模态对话框中的事件循环阻塞

用于并行 for 循环的 C++ OpenMP 指令?

java - 为什么我们有非静态函数/方法?

c++ - C++ 标准库的 Xcode 文档集

c++ - 处理孙子控件的 WM_NOTIFY

c++ - 将非原子加载到与原子变量相同的缓存行会导致原子变量失败吗?

c++ - 处理永远不会输入的 switch 情况的最合适方法是什么?

c++ - 为什么 std::transform 使用构造函数?

c++ - C++11 中的正则表达式

c++ - 从以 string_view 作为参数的函数返回字符串时出错