Integer division won't work, make the types double.
Everyone seems to forget to check for division by zero. With doubles this is a little trickier:
1 2 3 4 5 6 7
#include <cmath>
constdouble precision = 1e-3; // 0.001 set this to whatever you want
if (std::abs(b) < precision) {
std::cout "Division by zero error\n"
}
Place an else on line 36 to catch bad input. Or use a switch statement with a default: case, instead of the ifelseif chain.
#include <iostream>
usingnamespace std;
int main()
{
string name;
cout << "What's your name?\n";
getline (cin, name);
cout << "Hello, " << name << "!\n";
float a;
cout << "Enter a number \n";
cin >> a;
float b;
cout << "Enter another one \n";
cin >> b;
int x;
cout << "Choose a desired function: 1 for add, 2 for sub, 3 for multiply, 4 for divide \n";
cin >> x;
char function = 'x';
switch(x) //Changed function to x, as it will always be 'x' and nothing else.
{ //Also changed the cases to integers.
case 1 :
cout << "a+b=" << a+b << endl;
break;
case 2 :
cout << "a-b=" << a-b << endl;
break;
case 3 :
cout << "a*b=" << a*b << endl;
break;
case 4 :
cout << "a/b=" << a/b << endl;
break;
default :
cout << "Invalid input.\n";
}
//Got rid of result as your case already delivers that to you.
return 0;
}