-2

This is the series I've to find the sum of (upto x terms which user inputs):

1/1 + 1/3 + 1/5 + 1/7 + ...

Here is the code I wrote :

int x;
cout << "How many terms (x) you want to add the series till?\n\n ";
cin >> x;
float m, answer=0.0;
for (int n=0; n<x; n++)
{
  m=1/((2*n)+1);
  answer=answer+m;
}
cout << " \n The answer is " << answer;

However, the answer always comes as 1 so what I might be doing wrong here?

Kuba hasn't forgotten Monica
  • 95,931
  • 16
  • 151
  • 313

1 Answers1

2

The line

m=1/((2*n)+1);

is doing integer arithmetic on the right hand side, because all the values involved are integers. For n=0 you get 1/((2*0)+1) = 1/1 = 1, whereas for e.g. n=1 you get 1/((2*1)+1) = 1/3 = 0, which is then assigned to the float. Ultimately you get a 1 for the first term and zeroes for the rest, so the sum ends up being 1.

If you make any of the terms floating-point, like so:

m = 1.0 / (2 * n + 1);

then you'll get results like 1.0 / 3 = 0.333... instead.

You can see more detail about the rules for arithmetic operators here:

Daniel McLaury
  • 4,047
  • 1
  • 15
  • 37
  • Even better (or worse!), it only takes the lone period (`.`) to completely change this behavior: replace `1` with `1.`, and woe betide anyone who loses that period sometime later. When people ask what's wrong with C family of languages, such things are a prime example. – Kuba hasn't forgotten Monica Mar 05 '20 at 04:34
  • I would make it a `1.0f` as `m` is a `float`. – Stack Danny Mar 05 '20 at 04:42