series calculation

Hello.
why this code do not work correctly?

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
29
30
31
32
33
34
35
36
37
38
  #include <iostream>


using namespace std;

int main()
{

	int N=10;
	int n;
	float S1;
	float S2;

	for (n = 1; n <= N; n++)
	{
		if (n % 2 == 0)

		{
			S1 += n / (n + 1);

            cout << "S1 is : " << S1 << endl;

    		}

		if(n % 2 != 0){

			S2 += -(n / (n + 1));

           cout << "S2 is : " << S2 << endl;

		}


	}

	return 0;
}
> why this code do not work correctly?
> S1 += n / (n + 1);
Beware of integer division rounding down.

Your S1 and S2 are uninitialised as well.
You forgot to initialize S2 and S2.
S1 += n / (n + 1) is the same as saying S1 = S1 + n / (n + 1)
Without giving S1 and S2 initial values, this would be a semantic error.

So initialize S1 and S2 with 0 at the beginning.
float S1 = 0;
floay S2 = 0;
I try it already but the result will be zero!
Change the +1 in lines 19 and 27 to +1.0 and see what happens.

Then go back and re-read salem c's post.

thanks. I forget that S is float!
It's not so much that S1 and S2 are floats ... it's that n is an int.
Topic archived. No new replies allowed.