Help improve this calculator
Aug 23, 2013 at 3:37am UTC
I'm an ultimate beginner of
C++ . How do i make this calculator restart without re-running it? I heard of loops, but I'm still not sure how to use those. also, are there any ways to make this calculator more simple? instead of adding many if statements?
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
#include <iostream>
using namespace std;
int a;
int b;
string symbol;
int sum;
int main()
{
cout << "Hello and thank you for using this Calculator! \n\n" ;
cout << "Enter a number(s) \n" ;
cin >> a;
cout << " \n" ;
cout << "Now enter a symbol (+,-,*,%) \n" ;
cin >> symbol;
cout << " \n" ;
cout << "Enter another number(s) \n" ;
cin >> b;
cout << " \n" ;
if (symbol == "+" ){
sum = a+b;
cout << "The answer is " ;
cout << sum;
}else if (symbol == "-" ){
sum = a-b;
cout << "The answer is " ;
cout << sum;
}else if (symbol == "*" ){
sum = a*b;
cout << "The answer is " ;
cout << sum;
}else if (symbol == "%" ){
sum = a%b;
cout << "The answer is " ;
cout << sum;
}
return 0;
}
Aug 23, 2013 at 5:06am UTC
You can make it simpler by using switch statement, a char for the operation and just validate your input as you go
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
int num1, num2, sum;
char op;
while (std::cin >> num1 >> op >> num2)
{
switch (op)
{
case '+' :
sum = num1 + num2;
break ;
case '-' :
sum = num1 - num2;
break ;
}
// /, *, ...
std::cout << sum << std::endl;
}
Last edited on Aug 23, 2013 at 5:06am UTC
Aug 24, 2013 at 1:44am UTC
Thanks, ill try that!
Topic archived. No new replies allowed.