【发布时间】: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++