Beginner Help

I am practicing with functions and I made a simple calculator that calculates addition,subtraction,multiplication and division. When I tried to output the result, I was unable to receive the correct value. I highly suspects that my problem is within the function userinput.

Here is my 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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
using namespace std;

#include <iostream>
#include <string>

// We are making a simple calculator using multple functions.

int userinput(int x,int y,int z);
int add(int x,int y);
int subtraction(int x,int y);
int multiply(int x,int y);
int division(int x,int y);

int main()
{
    int first,second,choice,z;
    
    cout << "Please select your option, ";
    cout << "add - 1, minus - 2, multiply - 3, division - 4" << endl;
    cin >> choice;
    cout << "Enter first number: ";
    cin >> first;
    cout << "Enter second number: ";
    cin >> second;
    cout << "You choosed option " << choice << ", and your result is " 
    << z << ".";
    z = userinput(choice,first,second);
    return 0;
}

int userinput(int x, int y, int z) //Compile results and return the answer
{
    int result;
    
    if ( x == 1)
    {
        result = add(y,z);
    }
    else if ( x == 2)
    {
        result = subtraction(y,z);
    }
    else if ( x == 3)
    {
        result = multiply(y,z);
    }
    else
    {
        result = division(y,z);
    }
    
    return result;
}
int add(int x,int y)
{
    int z;
    
    z = x + y;
  
    return z;
}
int subtraction(int x,int y)
{
    int z;
    
    z = x - y;
    
    return z;
}
int multiply(int x, int y)
{
    int z;
    
    z = x * y;

    return z;
}
int division(int x,int y)
{
    int z;
    
    z = x / y;
    
    return z;
}
Last edited on
You're outputting the value of z before you actually calculate it.

Try moving line 27 above line 25.
Thanks! I was too focused on the UserInput function to notices it. :[
Also as you're a Begginer you mite not know this

But never use namespace std in big programmes it causes errors
If you continue with it you'll get a habit every time you use something from
The standard libary use std::

The reason it's bad it can cause errors from two namespaces search it up
Topic archived. No new replies allowed.