1

This is my code and i'm trying to calculate this series : ((-1)^n)*n/(n+1) that n started from 1 to 5, code is not working correctly, anyone can help ?

int main(){

    int i,n;
    double sum1;

    for (i=1; i<6; i++)

    sum1 += (pow(-1,i))*((i)/(i+1));

    cout<<sum1;

    return 0;
}

The true answer at the end must be equal to -0.6166666666666667 which code cant calculate it correctly. I calculated series from here. Is there any special function to do summation ?

Blaze
  • 16,736
  • 2
  • 25
  • 44
Elia
  • 31
  • 5

3 Answers3

2
  • Always init variables before usage. double sum1 = 0;

  • ((i) / (i + 1)) performs integer division, the result is 0 for any i.

  • Use for the pow function to find power of -1 is extremely irrational
int main() {

   int i;
   double sum1 = 0;
   double sign = -1;


   for (i = 1; i < 6; i++)
   {
      sum1 += sign * i / (i + 1);
      sign *= -1.0;
   }

   std::cout << sum1;

   return 0;
}
Dmytro Dadyka
  • 2,208
  • 5
  • 18
  • 31
2

Make sure to initialize your variables before you use them. You initialize i afterwards so it's fine like this, but sum1 needs to be initialized:

double sum1 = 0.0;

For the summation, even if the result is assigned to a double, the intermediate results might not be and integer devision result in truncated values. For this reason, double literals should be used (such as 2.0 instead of 2) and i should be casted where applicable:

sum1 += (pow(-1, i))*(((double)i) / ((double)i + 1.0));

Finally, to get the desired precision, std::setprecision can be used in the print. The final result could look like this:

int main() {
    int i;
    double sum1 = 0.0;

    for (i = 1; i < 6; i++)
        sum1 += (pow(-1, i))*(((double)i) / ((double)i + 1.0));

    std::cout << std::setprecision(15) << sum1  << std::endl;
    return 0;
}

Output:

-0.616666666666667

Blaze
  • 16,736
  • 2
  • 25
  • 44
-1

Try this instead

for (i = 0; i <= 5; i++) // from 0 to 5 inclusively
    sum1 += (pow(-1, i)) * (static_cast<double>(i) / (i + 1));
serge
  • 992
  • 5
  • 8