Returning functions

I am trying to do an assignment where I call from my second function to answer my first. There is not much in my book on how to do this the way the assignment asks. The information on calling values from functions is extremely limited, and I couldn't find much online relating to the problem i have.

The actual assignment is this:
Write a program that has two functions. The 1st function is the main function. The main function should prompt the user for three inputs: number 1, number 2, and an operator.

The main function should call a 2nd function called calculate. The 2nd function should offer the choices of calculating addition, subtraction, multiplication, and division. Use a switch statement to evaluate the operator, then choose the appropriate calculation and return the result to the main function.


Here is my code, it doesn't work and I'm not sure how I would make it work with the assignment:
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() //Asks for input
{
    char op{};
    double num1{}, num2{};
    

    cout << "Enter your first number: " << endl;
    cin >> num1;
    cout << "Enter your second number: " << endl;
    cin >> num2;
    cout << "Enter the desired operator: (add, sub, div, mult)" << endl;
    cin >> op;
    
    return num1, num2, op;
}

int calculate() //Calculates input values, provides answer for main function
{
    char op{ main() };
    double num1{ main() }, num2{ main() }, ans;

     // create switch to decide between operator, create equations for calculations, 

        switch (op)
        {
        case 'add': ans = num1 + num2; break;
        case 'sub': ans = num1 - num2; break;
        case 'div': ans = num1 / num2; break;
        case 'mult': ans = num1 * num2; break;
        default: cout << "Invalid input."; break;   
        }

        return ans;
}
Hello rovert456,

Your program starts out OK until you reach line 18. This will end the program, but the coma operator is not working the way that you think it is. The only value being returned by the program is "op".

You have created a function, but you never call it, so even though it is wrong it is never used.

First the variables you gave values to in "main" need to be sent to the function so that yo can use them.

"main" is the only function that is never called. This can be done, but it is not proper.

For a better understanding check out https://www.learncpp.com/ chapter 2. I have found their pages easy to understand and the examples are to the point.

Lastly the function "calculate" returns a value of "int". It should be a value of "double", but it is not important at the moment because the function is never called.

That should get you started. When you have fixed or changed it post it and we can go from there.

Andy
Hello rovert456,

When I got the program fixed up it will output this as an example:


 Enter your first number: 1
 Enter your second number: 2
 Enter the desired operator: (+, -, /, *): +

 1 + 2 = 3

 Press Enter to continue:


 Enter your first number: 1
 Enter your second number: 0
 Enter the desired operator: (+, -, /, *): /

     Can not divide by 0!

 1 / 0 = 0  // <--- Not accurate, but could use some work in "main".

 Press Enter to continue:


 Enter your first number: 1
 Enter your second number: 128
 Enter the desired operator: (+, -, /, *): /

 1 / 128 = 0.0078125

 Press Enter to continue:


Some suggestions:
In "main" cout << " Enter your second number: "; if you write the prompt like this without any "\n" or "endl" it puts the "cin" on the same line.

Notice that I changed the operator types from words to the symbols. This will make more sense shortly.

In the function write your "switch" like this:
1
2
3
4
5
6
7
8
switch (op)
{
    case '+':
        ans = num1 + num2;
        break;
    case '-':
        ans = num1 - num2;
        break;

"switch (op)" requires an "int" type value to work. Your "case 'add':"does not work. First you are trying to use a string that should have double quotes. Single quotes only work for single letters. Second strings are not allowed in case statements. Just as the parameter to the switch needs to be an "int" type so does the "case" statement. The "switch" parameter and the case statement need to match.

As you can see by the output I added to the case for "/" to deal with "num2" being (0), but this could be improved on as in allowing the user to enter a new value for "num2".

Andy

Edit:

Sorry I was interrupted. I meant to mention that writing the case statements as you did is fine, but consider the above code. In the beginning it helps make it easier to see what you are doing and find mistakes.
Last edited on
You can't enter add, sub etc as type char. You need to input as type string if you want this. If you want the switch statement like this, then you're got a conversion job to do. As per Andy, it's probably best to input as symbols.

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
#include <iostream>

using namespace std;

// Need to forward declare as used before definition
double calculate(double num1, double num2, char op);

int main()
{
	char op {};
	double num1 {}, num2 {};

	cout << "Enter your first number: ";
	cin >> num1;

	cout << "Enter your second number: ";
	cin >> num2;

	cout << "Enter the desired operator: (+ - / *): ";
	cin >> op;

	cout << '\n' << calculate(num1, num2, op);
}

double calculate(double num1, double num2, char op) //Calculates input values, provides answer for main function
{
	double ans {};

	// create switch to decide between operator, create equations for calculations,

	switch (op)
	{
		case '+': ans = num1 + num2; break;
		case '-': ans = num1 - num2; break;
		case '/': ans = num1 / num2; break;
		case '*': ans = num1 * num2; break;
		default: cout << "\nInvalid input.\n"; break;
	}

	return ans;
}

Thank you Andy and seeplus for the help! I appreciate you trying to let me figure it out on my own with some hints, but after looking at seeplus' code I don't think there would've been much hope for me understanding it, half of the stuff in his code wasn't even mentioned in my book! I'm planning on talking to my prof about it but I doubt that will help.

I tried incorporating what Andy said with the code seeplus provided, I think I got it for the most part. I understand the code now which I think is the most important part!

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

double calculate(double num1, double num2, char op);

int main() //Asks for input
{
    char op{};
    double num1{}, num2{};
    

    cout << "Enter your first number: "; cin >> num1;
    cout << "Enter the desired operator: (+, -, /, *): "; cin >> op;
    cout << "Enter your second number: "; cin >> num2;
       
    cout << "\n" << num1 << " " << op << " " << num2 << " = " << calculate(num1, num2, op) << endl;
}

double calculate(double num1, double num2, char op) // Calculates input values, provides answer for main function
{
    double ans;

     // Create switch to decide between operator, create equations for calculations

        switch (op)
        {
        case '+':
            ans = num1 + num2;
            break;
        case '-':
            ans = num1 - num2;
            break;
        case '/':
            ans = num1 / num2;
            break;
        case '*':
            ans = num1 * num2;
            break;
        default:
            cout << "Invalid input.";
            break;
        }       
        if ((op = '/') && (num2 = '0')) {
            cout << "\nYou can not divide by 0!";
            return 0;
        }
        return ans;
}

I would have never known to use "double" instead of "int" for the function. I had previously tried to use the operator symbols instead of words, but it didn't work out the first time around.
The if statement in calculate() should come first. You're dong the division and then checking if you should! Also, when testing numbers, you don't use '' as this implies a char. For equality comparison, use == rather than =. = means assignment, == means equality (is equal).

 
if ((op = '/') && (num2 = '0')) {


should be:

 
if ((op == '/') && (num2 == 0)) {



Alternatively, you can put a simpler if statement in the case '/'

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
double calculate(double num1, double num2, char op) // Calculates input values, provides answer for main function
{
	double ans {};

	// Create switch to decide between operator, create equations for calculations

	switch (op)
	{
		case '+':
			ans = num1 + num2;
			break;
		case '-':
			ans = num1 - num2;
			break;
		case '/':
			if (num2 == 0)
				ans = 0;
			else
				ans = num1 / num2;
			break;
		case '*':
			ans = num1 * num2;
			break;
		default:
			cout << "Invalid input.";
			break;
	}
	return ans;
}



Last edited on
that returns a random number if it defaults.

I would eliminate ans and rewire it to abuse the return statement

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
double calculate(double num1, double num2, char op) // Calculates input values, provides answer for main function
{	// Create switch to decide between operator, create equations for calculations

	switch (op)
	{
		case '+':
			return(num1 + num2);			
		case '-':
			return(num1 - num2);
		case '*':
			return(num1 * num2);
		case '/':      ///moved so it moves into default from here if bad
			if (num2)
				return(num1 / num2);

		default:
			cout << "Invalid input.";
			return(0.0);
	}
}
line 18:

as the guys said you can't return more than one variable in Python you can,

a way around this would be to create a struct with the two numbers and operator,

also very important you are returning an int, you should be returning double as both your local variables in the function are of double.
Last edited on
good catch on the int/double.

"a way around this would be to create a struct with the two numbers and operator"

or a tuple seems to be the preferred way these days, though what a tuple can do that a C-struct cannot, I do not know.
Registered users can post here. Sign in or register to post.