I need help with pass by value

The goal here is to use pass by value to calculate sum of (1/n)^2 aka: (1/1)^2 + (1/2)^2 +... (1/n)^2.
Im a beginner and so far i cannot understand what is wrong with my code.. I just keep on getting a blank result after my first output line

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

using namespace std;


double sum2(unsigned int);
unsigned int getValidPositiveInteger();

int main()
{
	unsigned int i = getValidPositiveInteger();
	cout << "Enter the number of terms in the partial sum approximation of the series (n): \n";
	cin >> i;
	cout << "Using pass by value, the partial term using " << i << " terms is: " << sum2(i);
	return 0;
}

double sum2(unsigned int n)
{
	double sum = 0, result;
	unsigned int a;
	for (a = 1; a <= n; ++a)
	{
		result = pow((1.0/a), 2);
		sum += result;
	}
	return (sum);
}

// 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
1. Why does line 23 call getValidPositiveInteger()?

2. Your main() has aqcuired a value "i" and given it to function sum2(). The sum2() thus has the given value in "n". What is the first thing you do in that function?

You do n = 1;. So long for the value gotten from the caller. Perhaps your loop should use a different variable?

3. 1 / n. That has integer (1) and unsigned int (n). Integer division. Integer division returns an integer. 1/1 returns 1. 1/n, where n>1, returns 0.

1.0 / n has double and unsigned int. There are no mixed operators. A double/double will be used and that produces a double.


4. Look at http://www.cplusplus.com/reference/cmath/pow/
and compare to your code. Do you notice anything fishy?

5. a^2 is easy to express as a*a.
Ok first of all thanks for replying.

I get your point for 3 and 5.

Ohh I see that I messed up mixed the exponent and the base for the pow format

For point 1 how am I supposed to call the value i input by the user?

And for point 2 you mean that I should write it as n=a and then declare that a=1?


Ok I managed to figure it all out thanks to you :)
Thank you so much for your help keskiverto!!
Last edited on
For point 2, what do I do here?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>

int foo( int n ) {
  int sum = 0;
  for ( int y = 1; y <= n; ++y ) {
    sum += y;
  }
  return sum;
}

int main() {
  int count = 3;
  int result = foo( count );
  std::cout << "1+2+3=" << result << '\n';
  return 0;
}
I understood it all. What was bugging me was that I was not getting it that when I gave my sum2() the value i; the value n was being assigned that same value i.
Topic archived. No new replies allowed.