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 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102
|
/**program description:
*
* simple calculator written for beginners.
* This program asks user to enter an arithmetic
* expression that contains two numbers and one
* operator. User will be given the result of the
* calculation. Operators allowed to be used
* are: + - * / % ...
*
* Author: X-Shab
* Copyright 2008 - 2009
*
*/
#include<iostream>
#include<string>
using namespace std;
const string EXIT = "-1";
void add(float num1, float num2)
{
cout<<"Result is: "<< num1 + num2 <<endl;
}
void subtract(float num1, float num2)
{
cout<<"Result is: "<< num1 - num2 <<endl;
}
void multiply(float num1, float num2)
{
cout<<"Result is: "<< num1 * num2 <<endl;
}
void divide(float numerator, float denominator)
{
if (denominator != 0)
cout<<"Result is: "<< numerator / denominator <<endl;
else
cout<<"You can not divide by denominator\n";
}
void modulus(float num1, float num2)
{
cout<<"Result is: "<< (int)num1 % (int)num2 <<endl;
}
int main(void)
{
string mathematicalOperation;
float num1, num2;
char operatorSign;
cout << "Please enter an arithmetic expression (-1 to Exit)\n";
cin >> mathematicalOperation;
//search for operator sign and perform calculation
while(mathematicalOperation.compare(EXIT))
{
int getFirstDigitIndex = mathematicalOperation.find_first_of("0123456789");
int operatorSignIndex = mathematicalOperation.find_first_of("+-*/%", getFirstDigitIndex);
if (operatorSignIndex != -1)
{
operatorSign = mathematicalOperation.at(operatorSignIndex);
string firstNumber = mathematicalOperation.substr(0,operatorSignIndex);
string secondNumber = mathematicalOperation.substr(operatorSignIndex + 1);
//convert numbers from string to float
num1 = (float)atof(firstNumber.c_str());
num2 = (float)atof(secondNumber.c_str());
switch(operatorSign)
{
case '+':
add(num1,num2);
break;
case '-':
subtract(num1,num2);
break;
case '*':
multiply(num1,num2);
break;
case '/':
divide(num1,num2);
break;
case '%':
modulus(num1,num2);
break;
}
}
cout<<"Please Enter Another Expression or Enter -1 to Exit:\n";
cin>>mathematicalOperation;
}
cout<<"SEE YOU LATER!\n";
return 0;
}
| |