#include <iostream>
usingnamespace std;
int add(int x, int y)
{
int z;
z = x + y;
return z;
}
int subtract(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 divide(int x, int y)
{
int z;
z = x / y;
return z;
}
int main()
{
int userChoice;
int x;
int y;
int r;
cout << "Please choose which operation you would like to preform: \n 1| Addition \n 2| Subtraction \n 3| Multiplication \n 4| Division" << endl;
cin >> userChoice;
switch (userChoice)
{
case 1:
cout << "Please enter the first number you would like to add: " << endl;
cin >> x;
cout << "Please enter the second number you would like to add: " << endl;
cin >> y;
r = add(x,y);
break;
case 2:
cout << "Please enter the minuend: " << endl;
cin >> x;
cout << "Please enter the subtrahend: " << endl;
cin >> y;
r = subtract(x,y);
break;
case 3:
cout << "Please enter the first number you would like to multiply: " << endl;
cin >> x;
cout << "Please enter the second number you would like to multiply: " << endl;
cin >> y;
r = multiply(x,y);
break;
case 4:
cout << "Please enter the dividend: " << endl;
cin >> x;
cout << "Please enter the divisor: " << endl;
cin >> y;
r = divide(x,y);
break;
default:
cout << "Please enter a number that corresponds to an operation!" << endl;
return -1;
break;
}
cout << r;
return 0;
}
is there a better way to make this so I don't have to use as much code. Is 83 lines too much? Does the amount of code even matter all that much?
Keep in mind I'm an absolute beginner.
Thanks,
tadtheob
Always check for division by zero. Division with integer types won't work so well: 1/3 is zero. Consider making them double instead.
Does the amount of code even matter all that much?
As long as the code is easy to read and understand and properly written, the amount of code doesn't matter. By properly written I mean things like no code duplication, proper use of functions etcetera.
As TheSmallGuy says there should be an option to Quit and an ability to continue. You can do this by using a bool variable:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
bool Quit = false;
while (!Quit) {
// prompt for user input
// get input
switch {
// ....
// ...
case 5:
Quit = true;
break;
default:
// ....
}
}
Get rid of return -1 in the default: case, it ends the program rather rudely :+)
Interestingly division by zero can be handled several ways - directly at the data entry point, at the function level or perhaps by exceptions or even assert(ions).