實現計算器的加法、減法、乘法和除法。使用一個命令行參數為您的選擇,和2個數字。你使用下面的數組來賦值操作符函數。
int add(int x, int y);
int sub(int x, int y);
int mul(int x, int y);
int div(int x, int y);
int (*pf[4])(int, int) = { add, sub, mul, div };
數據結構:函數指針數組
輸入:選擇運營商的數量(1,2,3,或4),
操作數的2個整數
輸出:操作結果
#include <iostream>
using namespace std;
int add(int x,int y){
return x+y;
}
int sub(int x,int y){
return x-y;
}
int mul(int x,int y){
return x*y;
}
int div(int x,int y){
return x/y;
}
int main(){
int (*pf[4])(int, int) = { add, sub, mul, div };
while(true){
cout<<"0. add"<<endl;
cout<<"1. sub"<<endl;
cout<<"2. mul"<<endl;
cout<<"3. div"<<endl;
cout<<"4. exit"<<endl;
cout<<"Select Operation :";
int opeNum;
cin>>opeNum;
if(opeNum==4){
return 0;
}
cout<<"Input 2 operand :";
int a,b;
cin>>a>>b;
cout<<"Result = "<<pf[opeNum](a,b)<<endl;
}
}