Repetitive Zero Terms

Hi,

I'm trying to write a simple C++ program to display the 1st 4 terms of a series as follows:

Ans = 1 - x^2/2! + x^4/4! - x^5/5!

The intended output is: 1 - number + number - number

The following is the code that I compiled:

#include <iostream>
using namespace std;

int factorial(int n)
{
if(n>1){
n=n*factorial(n-1);
}
else n=1;

return(n);
}

int main(){

int x,i,ans;

cout<<"Determine the expansion of:";
cin>>x;

cout<<"Ans = 1";

for(i=1;i<4;i++){

ans=((-1)^(i))*(x^(2*i))/factorial(2*i);

if(i=1,3)
cout<<"+"<<abs(ans);
else
cout<<"-"<<abs(ans);

}


return (0);
}

The problem is that everytime I run the compile program the output appears to be 1+0+0+0+0....all the way to infinity (I have to manually close the command prompt window).
I've looked over the code and can't seem to pinpoint what's causing this to happen. I'd be really grateful if someone could help me

Thanks,
Learner82
The line ans=((-1)^(i))*(x^(2*i))/factorial(2*i); isn't doing what you think it is doing. You're trying to use '^' to rasie a number to the power of i but '^' is actually a XOR Bitwise operator.

You should use the <cmath> library and use the power function.

http://www.cplusplus.com/reference/clibrary/cmath/
Also, ans is an integer, not a floating point number.
Topic archived. No new replies allowed.