Wrote program to sum terms, but can't get it to give me the correct summation...

I wrote this program to sum a user-defined number of terms for the series
1-1/2+1/3-1/4+1/5-...
But for some reason it's not working.
I have went line by line and everything makes since to me.
Can any body tell me wear I went wrong?

It only attempts to sum even numbers, and then it's incorrect.
It says 2 terms sum to 2, and any even number above that I try sums to 2 or 0.
:( can anyone please help?

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
39
40
41
42
43
44
45
46
47
48
 /*
Hannah, Loop-Sum, last modified 3/16/2015
 This program uses a loop to sum a user-defined number of terms, n, in the series
 1-1/2+1/3-1/4+1/5-...
*/

#include <iostream>
#include <iomanip>
#include <cmath>

using namespace std;
int main()
{
//Declare variables
	int n;
	double s, t, sum1, sum2, sum;
//Output program description, and ask for number of terms	
	cout << "This program uses a loop to sum a user-defined number of terms, n, in the series"
	     << "1-1/2+1/3-1/4+1/5-..." << endl;
	cout << "Please indicate how many terms you would like in the summation?\n";
		cin >> n;
//For loop selected, most straightforward way to do the summation		
if (n%2 ==0) //For even number of selected terms
	{
		for(n; n>0; n-=2) //adds the first n terms
		{
		s=(-1)*1/n;  //All even terms
		t=1/(n-1); //All odd terms
		sum1+=s; // This sums all even terms, which are negative for this series, thus added separately
		sum2+=t; // This sums all odd terms, which are positive for this series	
		}
	}
else //(2%n==1), For the odd number of selected terms
	{
		for(n; n>0; n-=2) //adds the first n terms
		{
		s=1/n;  //All odd terms
		t=(-1)*1/(n-1); //All even terms
		sum1+=s; // This sums all odd terms, which are positive for this series	
		sum2+=t; // This sums all even terms, which are negative for this series, thus added separately	
		}
	}
	sum=1+sum1+sum2;
	cout << "Using your indicated number of terms, your summation is " << setprecision(7) << sum;

	return 0;
}		
Last edited on
1/n == 0, when n is integer and 1<n. (Integer division discards the remainder.)

1.0/n is the fraction that you are looking for. (As accurately as a double can.)
Topic archived. No new replies allowed.