Skip to content

Instantly share code, notes, and snippets.

@arusso
Created June 18, 2012 00:43
Show Gist options
  • Save arusso/2946191 to your computer and use it in GitHub Desktop.
Save arusso/2946191 to your computer and use it in GitHub Desktop.
simple calculator
#include <iostream>
#include <string>
using namespace std;
// Function Declarations
int get_value(string msg);
char get_operator(string msg);
int compute(int lhs, int rhs, char op);
int main()
{
// Let's call a function to grab a value, and place the returned value
// into variable a
int a = get_value("Enter left-hand operand:");
// Let's call a function to grab the operator, and place the returned value
// into variable op
char op = get_operator("Enter operator:");
// Let's call a function to grab a value, and place the returned value
// into variable a
int b = get_value("Enter right-hand operand:");
// Compute the result of `a op b`
int result = compute(a,b,op);
cout << "Result: " << result << endl;
}
// Output a message to user, grab input for stdin
// Assumes that valid input is given
int get_value(string msg) {
int value = 0;
cout << msg << endl;
cin >> value;
return value;
}
// Output a message to user, grab operator from stdin
// Assumes that valid input is given
char get_operator(string msg) {
char op;
cout << msg << endl;
cin >> op;
return op;
}
int compute(int a, int b, char op) {
switch(op) {
case '+':
return (a + b);
break;
case '-':
return (a - b);
break;
case '*':
return (a * b);
break;
case '/':
return (a / b);
break;
default:
cout << "invalid operator passed!" << endl;
return -1;
break;
}
}
#include <iostream>
int Integer1();
char Operator();
int Integer2();
int DoMath(int a, char m, int b);
void Display(int result);
int main()
{
int a = Integer1();
char m = Operator();
int b = Integer2();
int result = DoMath(a, m, b);
Display(result);
}
int Integer1()
{
using namespace std;
cout << "Enter a number" << endl;
int a;
cin >> a;
return a;
}
char Operator()
{
using namespace std;
cout << "Enter your operator: +, -, *, or /" << endl;
char m;
cin >> m;
return m;
}
int Integer2()
{
using namespace std;
cout << "Enter your next number" << endl;
int b;
cin >> b;
return b;
}
int DoMath(int a, char m, int b)
{
using namespace std;
if (m == '+')
return a + b;
if (m == '-')
return a - b;
if (m == '*')
return a * b;
if (m == '/')
return a / b;
return 0;
}
void Display(int result)
{
using namespace std;
cout << "The answer is " << result << endl;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment