Hey I need help with pass by reference

Hello! The goal here is to get the sum of (1/n)^2 aka: (1/1)^2 + (1/2)^2 +...(1/n)^2.
Im using pass by reference to try to get the task done but I keep on getting a wrong result. Can somebody help me pinpoint my errors please.



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
 #include "stdafx.h"
#include "stdafx.h"
#include <iostream>
#include <cmath>

using namespace std;


void sum1(double&, unsigned int);  //This string was given
unsigned int getValidPositiveInteger();

int main()
{
	unsigned int i = getValidPositiveInteger();
	double sum;
	cout << "Enter the number of terms in the partial sum approximation of the series (n): \n";
	cin >> i;
	sum1(sum, i);
	cout << i << "     " << sum << endl;
	return 0;
}

void sum1(double& sum, unsigned int n)
{
	unsigned int c;
	for (c = 1; c <= n; ++c)
	{
		sum += (1.0 / c)*(1.0 / c);
	}
}


// Get a valid integer from the user
unsigned int getValidPositiveInteger() {
	int userInput;

	cin >> userInput;

	while (cin.fail() || userInput < 0) {
		cin.clear();
		cin.ignore();
		cout << "Please enter a positive integer only\n";
		cin >> userInput;
	}

	return userInput;
}
Last edited on
Line 15: sum isn't initialized - and it should be, to zero.

You should get into the habit of compiling with all warnings on - most modern compilers would have warned you about the use of an uninitialized value, which is undefined behavior.
Ahh I see it now. Thanks for the reply and tips mbozzi :)
Topic archived. No new replies allowed.