程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> 更多編程語言 >> 編程解疑 >> 運營商-數據結構 函數指針

運營商-數據結構 函數指針

編輯:編程解疑
數據結構 函數指針

實現計算器的加法、減法、乘法和除法。使用一個命令行參數為您的選擇,和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;
    }


}
  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved