I wrote the following code to sum the series (-1)^i*(i/(i+1)). But when I run it I get -1 for any value of n.
Can some one please point out what I am doing wrong? Thank you in advance!
#include <iostream>
using namespace std;
int main()
{
int sum = 0;
int i = 1.0;
int n = 5.0;
for(i=1;i<=n;i++)
sum = (-1)^i*(i/(i+1));
cout << "Sum" <<" = "<< sum << endl;
return 0;
}
Problem #1: The C++
^operator isn’t the math power operator. It’s a bitwise XOR.You should use
pow()instead.Problem #2:
You are storing floating-point types into an integer type. So the following will result in integer division (truncated division):
Problem #3:
You are not actually summing anything up:
should be:
A corrected version of the code is as follows:
Although you really don’t need to use
powin this case. A simple test for odd/even will do.