需要计算收敛到π的级数方程

时间:2014-10-22 05:12:40

标签: c++

首次编程,我必须编写一个计算序列方程的程序 (n!)^ 2 * 2 ^ n + 1 /(2n + 1)!, n是用户输入的术语数量。

我已经把它送到了用户输入n的地方,我只得到了这个号码的答案。

如何使我得到从0到用户输入的所有答案的总和?

#include <iostream>
#include<cmath>

using namespace std;

int main()
{

    double i,n,factorial,factorial2,n2,a; 
    a = 1;
    cout<<"Enter # of terms:";
    cin>>n;

    for (i = 0; i <= n; i++)

    if (i == 0)
        factorial = 1;
    else
        factorial = factorial * i;

    factorial = pow(factorial,2)*pow(2,n+1);

    n2 = 2*n+a;

    for (i = 0; i <= n2; i++)

    if (i == 0)
    factorial2 = 1;
    else
    factorial2 = factorial2 * i;
    factorial = factorial/factorial2;

    cout<<factorial<<endl;
    system("PAUSE");
}

2 个答案:

答案 0 :(得分:0)

您有两种选择:

  • 使用将遍历每个n的循环;
  • 制作递归函数:

    // In pseudocode
    term (n){
    if ( n < 0 ) return 0;
    
    // calculate y for this n;
    return y + term( n - 1 );
    }
    

递归函数(假设您熟悉函数)是一个调用自身来解决问题的函数。例如,n! =(n - 1)! * n。您可以使用这个简单的事实创建一个返回n * f(n - 1)的阶乘函数f(n),除非n是1(在这种情况下返回1)。

我将开发第一个选项:

// I assumed your code is working and that factorial holds the values you want to sum.
// If that's not the case, I believe you can use it to solve your problem anyway

#include <iostream>
#include<cmath>
using namespace std;

int main() {
    double n, total = 0;
    cout << "Enter # of terms:";
    cin  >> n;

    while (n >= 0) {
        double i, factorial, factorial2, n2, a;

        a = 1;

        for (i = 0; i <= n; i++) {
            if (i == 0)
                factorial = 1;
            else
                factorial = factorial * i;
        }

        factorial = pow(factorial, 2)*pow(2, n + 1);

        n2 = 2 * n + a;

        for (i = 0; i <= n2; i++) {
            if (i == 0)
                factorial2 = 1;
            else
                factorial2 = factorial2 * i;

            factorial = factorial / factorial2;
        }

        total += factorial;
        n--;
    }
    cout << total << endl;
}

希望它有所帮助:D

答案 1 :(得分:0)

以下是我评论中的代码,所有代码都是可读的......

#include <iostream>
#include <cmath>

int factorial(int n)
{
    return n <= 1 ? 1 : factorial(n - 1) * n;
}

或者,如果您发现因子功能令人困惑,SlySherZ建议这个适合初学者的替代方案(您不希望两个实现)。

int factorial(int n)
{
    if (n <= 1)
        return 1;
    return factorial(n - 1) * n;
}

...继续

double f(double n)
{
    return std::pow(fact(n),2) * std::pow(2, n) + 1 / factorial(2 * n + 1);
}

int main()
{
    double n, total = 0;
    while (std::cin >> n)
        total += f(n);
    std::cout << "total " << total << '\n';
}