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

Need to calculate series equation converging to π

本文关键字:方程 计算      更新时间:2023-10-16

第一次编程时,我必须编写一个计算级数方程的程序(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");
}

这是我的评论中的代码,所有这些都是可读的。。。

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

您有两个选项:

  • 使用一个循环来遍历每个n
  • 制作递归函数:

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

递归函数(假设你熟悉函数)是一个调用自己来解决问题的函数。例如,n!=(n-1)!*n.您可以使用这个简单的事实创建一个阶乘函数f(n),它返回n*f(n-1),除非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