basic calculator

been a while since ive done this so i decided to do it again after not having a computer for a while. Im trying to have the user enter 1 - 4 for add, subtract, multiply, and divide. when the choice is entered i want the main fuction to call the correct function. but is not working when call the function from main function.

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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
// Include
#include <iostream>
using namespace std;

// Main
int main()
{
    // Basic Calculator
    int number;
    
    cout << "1. ADD" << endl;
    cout << "2. Subtract" << endl;
    cout << "3. Multiply" << endl;
    cout << "4. Divide" << endl;
    
    cout << "\n";
    
    cout << "Please choose 1-4: ";
    cin >> number;
    
    if (number == 1)
       add();
    else if (number == 2)
       subtract();
    else if (number == 3)
       multiply();
    else if (number == 4)
       divide();
    
    return 0;
}
// Add
int add()
{
    int num1;
    int num2;
    int total;
    
    cout << "\nPlease enter 1st number: ";
    cin >> num1;
    cout << "Please enter 2nd number: ";
    cin >> num2;
    
    total = num1 + num2;
    
    cout << "\nYour total is: " << total;
    
    cout << "\n";
    
    return 0;
}
// Subtract
int subtract()
{
    int num1;
    int num2;
    int total;
    
    cout << "\nPlease enter 1st number: ";
    cin >> num1;
    cout << "Please enter 2nd number: ";
    cin >> num2;
    
    total = num1 - num2;
    
    cout << "\nYour total is: " << total;
    
    cout << "\n";
    
    return 0;
}
// Multiply
int multiply()
{
    int num1;
    int num2;
    int total;
    
    cout << "\nPlease enter 1st number: ";
    cin >> num1;
    cout << "Please enter 2nd number: ";
    cin >> num2;
    
    total = num1 * num2;
    
    cout << "\nYour total is: " << total;
    
    cout << "\n";
    
    return 0;
}
// Divide
int divide()
{
    int num1;
    int num2;
    int total;
    
    cout << "\nPlease enter 1st number: ";
    cin >> num1;
    cout << "Please enter 2nd number: ";
    cin >> num2;
    
    total = num1 / num2;
    
    cout << "\nYour total is: " << total;
    
    cout << "\n";
    
    return 0;
}
in c++ the compiler needs your help.
you can't say add in main. What is add? It has not seen anything like that yet (its below main).

to fix this you can make headers for the functions above main:
int add(); //its the same as the start of the function with a ; on the end.

also consider moving the identical parts out of each function. generally speaking its better to split the user interface (cin, cout here) from the work being done (add, subtract, etc here) and here that is extra nice because it avoids repeating the same code 4 times (one key point of a function is to avoid repeated code!).

total implies addition. maybe say your result is.
Last edited on
Okay, I see, thank you.
Hello Reaper1992,

I looked over your program and put some comments in the program along with some changes that might help:
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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
// Include
#include <iostream>

using namespace std;  // <--- Best not to use.

// <--- Forward declarations or prototypes go here.
// <--- See jonnin's reply.

// Main
int main()
{
    // Basic Calculator
    int number;  // <--- ALWAYS initialize all your variables.
    // <--- "num1" and "num2" should be defined here and passed to the functions.
    // You may also want to define "result" here to catch the return value of the functions.

    cout << 
        "1. ADD\n"
        "2. Subtract\n"
        "3. Multiply\n"
        "4. Divide\n\n"
        "Please choose 1-4: ";
    cin >> number;

    if (number == 1)
        add();
    else if (number == 2)
        subtract();
    else if (number == 3)
        multiply();
    else if (number == 4)
        divide();

    return 0;
}
// Add
int add()
{
    //**************************************
    // These lines should be in "main".
    int num1;
    int num2;
    int total;  // <--- You can do without this one.

    cout << "\nPlease enter 1st number: ";
    cin >> num1;

    cout << "Please enter 2nd number: ";
    cin >> num2;
    //***************************************
    total = num1 + num2;

    cout << "\nYour total is: " << total;  // <--- should be in "main".

    cout << "\n";

    return 0;  // <--- Should be returning "total", but it is never used in "main" so it really does not matter. Same for the other functions.
}
// Subtract
int subtract()
{
    int num1;
    int num2;
    int total;

    cout << "\nPlease enter 1st number: ";
    cin >> num1;

    cout << "Please enter 2nd number: ";
    cin >> num2;

    total = num1 - num2;

    cout << "\nYour total is: " << total;

    cout << "\n";

    return 0;
}
// Multiply
int multiply()
{
    int num1;
    int num2;
    int total;

    cout << "\nPlease enter 1st number: ";
    cin >> num1;
    cout << "Please enter 2nd number: ";
    cin >> num2;

    total = num1 * num2;

    cout << "\nYour total is: " << total;

    cout << "\n";

    return 0;
}
// Divide
int divide()
{
    int num1;
    int num2;
    int total;

    cout << "\nPlease enter 1st number: ";
    cin >> num1;

    cout << "Please enter 2nd number: ";
    cin >> num2;

    total = num1 / num2;

    cout << "\nYour total is: " << total;

    cout << "\n";

    return 0;
}

Some things to think about:
For the menu you do not need a "cout" for each line. In this case each line in double quotes is in the end considered 1 big string. The format just makes it easier to work with and it looks very much like you will see on the screen.

Right now it is not necessary as the program only runs once, but if you use a do/while or while loop in "main" you will need to add a choice 5 for "Exit".

The if/else if statements are fine, but you might want to consider a "switch".

As jonnin said a function should generally do 1 thing and return something if needed. As an example the "add" function could simply be:
1
2
3
4
int add(int num1, int num2)
{
    return num1 + num2;
}

This will work for "add", "subtract" and "multiply", but "divide" should have a little more. Either in "main" or the function you need to check that "num2" is not (0)zero before you actually divide. After that the function would end with return num1 / num2;.

Consider making your "num1" and "num2" "double"s instead of "int"s. This gives you more to work with and the division will produce a better result than integer division.

Andy
Perhaps something like:

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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
#include <iostream>
#include <string>
#include <limits>
#include <utility>
#include <cctype>

using Nums = std::pair<double, double>;

double add(double n1, double n2);
double subtract(double n1, double n2);
double multiply(double n1, double n2);
double divide(double n1, double n2);

template<typename T = int>
auto getNum(const std::string& prm)
{
	const auto notsp {[&]() {while (std::isspace(static_cast<unsigned char>(std::cin.peek())) && std::cin.peek() != '\n') std::cin.ignore(); return std::cin.peek() != '\n'; }};
	T n {};

	while ((std::cout << prm) && (!(std::cin >> n) || notsp())) {
		std::cout << "Not a number\n";
		std::cin.clear();
		std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
	}

	std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
	return n;
}

Nums get2Nums()
{
	const double num1 {getNum<double>("Please enter 1st number: ")};
	const double num2 {getNum<double>("Please enter 2nd number: ")};

	return {num1, num2};
}

int main()
{
	int number {};

	do {
		std::cout << "\n1. Add\n"
			<< "2. Subtract\n"
			<< "3. Multiply\n"
			<< "4. Divide\n"
			<< "0. Quit\n\n";

		number = getNum("Please choose 1 - 4: ");

		if (number >= 1 && number <= 4) {
			const auto nums {get2Nums()};
			double result {};

			switch (number) {
				case 1:
					result = add(nums.first, nums.second);
					break;

				case 2:
					result = subtract(nums.first, nums.second);
					break;

				case 3:
					result = multiply(nums.first, nums.second);
					break;

				case 4:
					result = divide(nums.first, nums.second);
					break;

				case 0:
					break;
			}

			std::cout << "\nResult is " << result << '\n';
		} else
			if (number)
				std::cout << "Invalid option\n";

	} while (number);
}

double add(double n1, double n2)
{
	return n1 + n2;
}

double subtract(double n1, double n2)
{
	return n1 - n2;
}

double multiply(double n1, double n2)
{
	return n1 * n2;
}

double divide(double n1, double n2)
{
	return n1 / n2;
}

Why is it that everyone seems to forget to check for division by zero ? Left as an exercise for the OP:+)
Obviously.... :)

My above code just displays inf for division by 0 as it's using double. And 0 / 0 displays nan(ind). The result is only used for display and not for other arithmetic operations.


Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
#include <map>
using namespace std;

int main()
{
   map<char,double (*)( double, double )> F =
      {  { '+', []( double a, double b ){ return a + b; } },
         { '-', []( double a, double b ){ return a - b; } },
         { '*', []( double a, double b ){ return a * b; } },
         { '/', []( double a, double b ){ return a / b; } }  };
   double a, b;
   char op;
   
   cout << "Input a op b, where op is one of +, -, *, / \n";
   cin >> a >> op >> b;
   cout << F[op]( a, b ) << '\n';
}


Input a op b, where op is one of +, -, *, / 
5*15
75
Last edited on
Registered users can post here. Sign in or register to post.