Hi, I am new to c++, and I have encountered a problem in my calculator program. When I execute it with any number or operational(except divide by 0), it shows "Please enter a valid operation". How to do I make it so that it will be functioning properly?
#include <iostream>
#include <string>
#include <cmath>
usingnamespace std;
double cal(double &x, double &y);
int result;
char op; //The operation
double firstnum;
double secondnum;
int main()
{
cout << "Please insert your first number" << endl;
cin >> firstnum;
cout << "Please insert operator" << endl;
cin >> op;
cout << "Please insert your second number" << endl;
cin >> secondnum;
if (op = '/' && secondnum == 0)
{
cout << "Attempting to divide by 0? You will blow up the world!!!" << endl;
}
else{
cal (firstnum, secondnum);
}
return 0;
}
double cal(double &x,double &y)
{
x = firstnum;
y = secondnum;
switch (op)
{
case'+':
result = x + y;
cout << "The answer is " << result << endl;
break;
case'-':
result = x - y;
cout << "The answer is " << result << endl;
break;
case'*':
result = x * y;
cout << "The answer is " << result << endl;
break;
case'/':
result = x / y;
cout << "The answer is " << result << endl;
break;
default:
cout << "Please enter a valid operation" << endl;
break;
}
}
Your main problem here is on line 21: if (op = '/' && secondnum == 0)
You forgot to put a second = for op == '/'.
Other than that, your cal function doesn't actually return anything, although you say that it returns a double, and global variables are nasty (don't use them if you can help it).