1 //---------------+-*/%算法---------------------------------------------------------- 2 #include <iostream> 3 using namespace std; 4 // 函数原型声明 5 int Add(int e1, int e2); 6 int Sub(const int*pe1, const int*pe2); 7 int Mul(const int&re1, const int&re2); 8 int Div(int e1, int e2)throw(int); // 分母不能为0,否则抛出除0错 9 int Mod(int e1,int e2)throw(int,long); //分子 分母不能为0,否则抛出无意义错或除0错 10 11 void main() { 12 int e1, e2, result; 13 char optr; 14 15 while (true) { 16 cout << 17 "Please type in an expression which likes a @b,type 'q' to quit" << endl; 18 cin >> optr; 19 if (optr == 'q' || optr == 'Q') 20 break; // 结束循环 21 cin.putback(optr); // 将读入的字符退回到流中,让它可以被重新读入 22 cin >> e1; 23 cin >> optr; 24 cin >> e2; 25 26 switch(optr) { 27 case '+': 28 result = Add(e1, e2); 29 break; 30 case '-': 31 result = Sub(&e1, &e2); 32 break; 33 case '*': 34 result = Mul(e1, e2); 35 break; 36 case '/': 37 result = Div(e1, e2); 38 break; 39 case '%': 40 result = Mod(e1, e2); 41 break; 42 } 43 } 44 system("pause"); 45 } 46 47 int Add(int e1, int e2) { 48 int result = e1 + e2; 49 cout << '=' << result << endl; 50 return result; 51 } 52 53 int Sub(const int *pe1, const int *pe2) { 54 int result = *pe1 - *pe2; // 指针指向的内存地址里面存的数值相减 55 cout << '=' << result << endl; 56 return result; 57 } 58 59 int Mul(const int &re1, const int &re2) { 60 int result = re1 * re2; 61 cout << '=' << result << endl; 62 return result; 63 } 64 65 int Div(int e1, int e2)throw(int) { 66 try { 67 if (e2 == 0) 68 throw 0; 69 int result = e1 / e2; 70 cout << '=' << result << endl; 71 return result; 72 } 73 catch(int) { 74 cout << "Denominator cannot be zero" << endl; 75 } 76 77 } 78 79 int Mod(int e1,int e2)throw(int,long) 80 { 81 try 82 { 83 if(e1==0) 84 throw int(0); 85 if(e2==0) 86 throw long(0); 87 88 int result=e1%e2; 89 cout << '=' << result << endl; 90 return result; 91 } 92 catch(int) 93 { 94 cout<<"It doesn't make sense when numerator is zero"<<endl; 95 } 96 catch(long) 97 { 98 cout<<"Denominator cannot be zero"<<endl; 99 } 100 }