Assistance with functions

Need help writing this program where main calls a function to ask user for set of numbers and then calls another function to calculate those numbers and finds the middle number. Comments are on the code.






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
#include <iostream>
using namespace std;

int middle(int numMid1, int numMid2, int numMid3)
{
	if ((num1 < num2) && (num3 > num2) || (num3 < num2) && (num1 > num2))
	{	
		numMid1 = num2;
	}
	if ((num3 < num1) && (num2 > num1) || (num2 < num1) && (num3 > num1))
	{
		numMid2 = num1;
	}
	if ((num2 < num3) && (num1 > num3) || (num1 < num3) && (num2 > num3))
	{
		numMid3 = num3;
	}

	// dont know what to return here
}

int getMiddle(int num1, int num2, int num3)
{
		int numVal;
		cout << "Enter value 1: ";
		cin >> num1;
		cout << "Enter value 2: ";
		cin >> num2;
		cout << "Enter value 3: ";
		cin >> num2;

		numVal = middle(num1, num2, num3); //dont know if this calls the above function
	}
}
	


closed account (o3hC5Di1)
Hi there,

That's pretty close, but the problem is in your middle() function.
As far as I can tell from this code, middle() has no access to the num1-3 variables.
In itself it doesn't need access to them, as you're passing numMid1-3, which take their place.

I would rewrite as such:

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
#include <iostream>
using namespace std;

int middle(int num1, int num2, int num3)
{
	if ((num1 < num2) && (num3 > num2))
	{	
		return num2;
	}
	else if ((num3 < num1) && (num2 > num1))
	{
		return num1;
	}
	else
	{
		return num3;
	}
}

int getMiddle()  //you don't need to pass anything here
{
		int numVal; //this isn't used?
                int num1, num2, num3;  // just declare these here and you're fine
		cout << "Enter value 1: ";
		cin >> num1;
		cout << "Enter value 2: ";
		cin >> num2;
		cout << "Enter value 3: ";
		cin >> num2;

		return middle(num1, num2, num3); //dont know if this calls the above function - it does
}


Hope that helps.
Let us know if you have any further questions.

All the best,
NwN
Topic archived. No new replies allowed.