N
N
Name_232021-11-13 14:39:14
C++ / C#
Name_23, 2021-11-13 14:39:14

Sum of an infinite series in C++?

The picture shows a formula that requires C++ code.
The code itself works, but I'm not sure if I wrote the formula correctly:

#include <iostream>
#include <cmath>

using namespace std;

long double Fact2(int n){
if (n < 0)
return 0;
else if (n==1 || n==0)
return 1;
else
return n*Fact2(n-1);
}

 int main()
 {
  int x , k =0;
  double eps, i, sum;

do{
    std::cout << "X=";
    std::cin >> x;
    if (x==0)
    cout << "incorect vaule x" << endl;
}while (x==0);

 do{
    std::cout << "eps=";
    std::cin >> eps;
    if (eps<=0 || eps>=1)
    cout << "incorect vaule eps" << endl;
}while (eps<=0 || eps>=1);

do{
    i = (pow(-1,k) * (pow(x, k+2) / Fact2(k+1) * (4 * k+3)) );
    cout << "k=" << k << "; U=" << i << "; Sum=" << sum << endl;
    sum +=1;
    k++;
}while(abs(i) > eps);

cout << "S=" << sum << endl;
cout << "n=" << k << endl;
return 0;

}


618fa36a18e26131463845.jpeg

Answer the question

In order to leave comments, you need to log in

1 answer(s)
G
galaxy, 2021-11-13
@galaxy

At least:
double eps, i, sum; -> double eps, i, sum = 0;

i = (pow(-1,k) * (pow(x, k+2) / Fact2(k+1) * (4 * k+3)) );
->
i = (pow(-1,k) * (pow(x, k+2) / Fact2(k+1) / (4 * k+3)) );

sum +=1; -> sum += i;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question