My bugged calculator.

Hello everyone! I just started learning C++ 3 days ago and today I decided to test my skill and try to make a calculator which does addition, subtraction, multiplication and division. I got it to work but only for integers. I noticed that all my variables were int so I changed them to double. Anyway, here is the code please post your comments and corrections. Thank you for your 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
#include <iostream>
#include <limits>
using namespace std;
int addition (double a, double b)
{
	double r;
	r=a+b;
	return (r);
}
int subtraction (double a, double b)
{
	double r;
	r=a-b;
	return (r);
}
int multiplication (double a, double b)
{
	double r;
	r=a*b;
	return (r);
}
int division (double a, double b)
{
	double r;
	r=a/b;
	return (r);
}

int main ()
{
	double x;
	int operation_type;
	double y;
	double result;
	cout << "Please enter the first variable: ";
	cin >> x;
	loop:
	cout << "Please select:\n(1) for addition \n(2) for subtraction\n(3) for multiplication\n(4) for division\n";
	cin >> operation_type;
	if (operation_type>4) {
		cout << "\nError!Invalid operation type.\n";
		goto loop;
	}
	if (operation_type<1) {
		cout << "\nError!Invalid operation type.1\n";
		goto loop;
	}
	cout << "Please enter the second variable: ";
	cin >> y;
	switch (operation_type) {
	case 1: result = addition (x,y);
			break;
	case 2: result = subtraction (x,y);
			break;
	case 3: result = multiplication (x,y);
			break;
	case 4: result = division (x,y);
			break;
	}
	cout << "The result is: " << result;
	std::cin.ignore ( std::numeric_limits<std::streamsize>::max(), '\n' );
  std::cin.get();
	return 0;
}



all your functions return ints, changing that would help

eg:
1
2
3
4
5
6
int double addition (double a, double b)
{
	double r;
	r=a+b;
	return (r);
}


This function could be shortened in
1
2
3
4
double addition (double a, double b)
{
    return a+b;
}

And you can even avoid those functions:
1
2
3
4
5
6
7
8
9
10
switch (operation_type) 
{
    case 1: 
        result = x+y;
        break;
    case 2: 
        result = x-y;
        break;
    //...
}

Last edited on
2 Bodwin: What compiler you using?
Thanks Bazzy that worked great. Thanks for the useful tips the program would be much smaller that way.

Zipuch I am using Borland Developer Studio 2006 which has C++ Builder in it so I think that's the name of the compiler. I am not sure about the version of C++ Builder and I don't know where to check it.

Anyway, thanks a lot for your help guys and have a good one.
Topic archived. No new replies allowed.