Oct 12, 2013 at 7:12pm UTC
I tried to make a calculator (which I thought would be easy) but then I encountered a problem. This is the code:
#include <iostream>
using namespace std;
int main()
{
int a;
int b = 0;
int result;
cout << "Enter a calculation: \n";
cin >> a;
result = a + b;
cout << "The answer is: " << result << endl;
cout << " \n";
return 0;
}
If I for example write 7+8, the answer I get is 7 (which is not correct). Test it if you want.
Oct 12, 2013 at 7:18pm UTC
Step your program.
Step by step, you'll understand "a" can only store a value.
So, inserting 7+8, "a" will only store the first valid numeric value (7).
Also, for logic's sake, "b" was 0 and was not into any operation. You can't expect "b" to have a different value.
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
#include <iostream>
int main()
{
int a;
int b;
int result;
char operation;
bool valid = 1;
std::cin >> a >> operation >> b;
switch (operation)
{
case '+' :
result = a+b;
break ;
case '-' :
result = a-b;
break ;
case '*' :
result = a*b;
break ;
case '/' :
result = a/b;
break ;
default :
valid = 0;
std::cout << "Invalid Operation" << std::endl;
}
if (valid)
std::cout << result << std::endl;
return 0;
}
Last edited on Oct 12, 2013 at 7:22pm UTC