用泰勒方法和循环计算圆周率
Calculating Pi with Taylor Method C++ and loop
圆周率的近似值可以用下面给出的级数来计算:
用这个级数写一个c++程序来计算圆周率的近似值。程序的输入n决定了pi值近似值的项数,并输出近似值。包括一个循环,允许用户对新值n重复这个计算,直到用户说她或他想结束程序。π= 4 * (1 - 1/3 + 1/5 - 1/7 + 1/9 ... + ((- 1) ^ n)/(2 n + 1)]
预期结果是:输入要近似的项数(或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;
}
相关文章:
- 当 A 在 for 循环中调用函数 B 时,如何计算函数 A 的空间复杂度?
- 如何编写计算功率的循环
- 在循环条件 i<sqrtN(预先计算)和 i*i<N 中,C++哪个更有效?
- 如果代码包含多个复杂度循环,如何计算复杂度
- C++在不使用pow或循环的情况下计算一个数字的幂
- 计算递归和时的无限循环
- 使用与 openmp C++并行的循环计算矩阵中每一行的最小值
- getline() 在 while 循环条件中如何计算为真或假?
- 为什么 g++ 将计算拉入热循环
- 计算使用 C++ std 函数而不是 for 循环的大 O
- 使用一个WALE循环计算AVG测试得分
- C++ (for) 循环:计算 y=n/(n+1)
- (C++)使用while循环计算平均数
- 尝试使用for循环计算Pi只给出3
- 基本的依偎循环计算1 - 239之间的质数,包括
- 循环计算矩形面积的公式
- c++ 11基于范围的for()循环计算一次或多次
- 使用while循环计算前n个斐波那契数的程序
- 使用while循环计算数学常数e
- 用泰勒方法和循环计算圆周率