Need help for my homework

by input x & n :
+(x/1!)-(x^2/2!)+(x^3/3!)- ... (x^n/n!) = ?
I do it without 'n' but I don't know how limit above series.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
  
#include <iostream>
using namespace std;
int main()

{
float n,x,sum=0,t=-1;
cout<<"Enter a Number : ";
cin>>x;
cout<<"\n"<<"Press Enter to calculate x- (x^2/2!) + (x^3/3!)- ... + (x^9/9!) - (x^10/10!)";
cin.ignore();
cin.get();
for(n=1;n<=10;n++)
{
	t=(-x/n)*t;
	sum=t+sum;
	cout<<n<<"="<<t<<"\t\n";
}
cout<< "SUM of them is = " <<sum;
cin.ignore();
cin.get();
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <iostream>

int main()
{
    double x ;
    std::cout << "x? " ;
    std::cin >> x ;

    int n ;
    std::cout << "n? " ;
    std::cin >> n ;

    std::cout << "\nx == " << x << "\ncalculate x - (x^2/2!) + (x^3/3!) - ... "
              << ( n%2 ? '+' : '-' ) << " (x^" << n << '/' << n << "!)\n\n" ;

    double term = x ;
    const int s = -1 ;
    double result = term ;

    for( int i = 2 ; i <= n ; ++i )
    {
        std::cout << std::showpos << term << ' ' ;
        term = ( term * s ) / i ;
        result += term ;
    }

    std::cout << term << "\n== " << result << '\n' ;
}

http://coliru.stacked-crooked.com/a/cd6f43363744bd1e
That's pretty cool. I think line 23 is more simply written as

 
        term = -term / i;


But where are the powers of x being calculated?
1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>
using namespace std;

int main ()
{
   int N;
   double x, sum = 0;
   cout << "Input N (>0): ";   cin >> N;
   cout << "x: ";    cin >> x;
   for ( ; N; N-- ) sum = ( 1 - sum ) * x / N;
   cout << "Result: " << sum;
}
@lastchance, Nice one! That seems to be correct. I'm still trying to fathom the (1 - sum) part, but it does seem to get the correct answer.
It's more influenced by how I would evaluate polynomials, @tpb. Usually I would follow @JLBorges' term-by-term sum (with the missing x factor) to evaluate power series, because I wouldn't usually know N.

FWIW, for large N the series tends to 1-exp(-x).
Topic archived. No new replies allowed.