2015-09-04 90 views
2

So..I明白,如果我走(*ptr)的一些函數f然後如何執行函數指針的算術運算?

res = (*ptr)(a,b) is the same as res = f(a,b). 

所以現在我的問題是,我有3個整數閱讀。前兩個是操作數,第三個是操作員,例如1 = add, 2 = subtract, 3 = multiply, 4 = divide。如果沒有if或switch語句,我該怎麼做。

我在想兩個可能的解決方案

  1. 創建4個三分球和每個指針尊重算術運算,但我還是得做一些輸入 驗證這需要如果或開關語句

  2. 這不是一個真正的解決方案,但基本的想法可能會像。如果C =運算符,然後我可以以某種方式做類似解析度= (* PTRC)(A,B),但我不認爲有對C

樣品輸入

1 2 1 

1 2 2 

1 2 3 

1 2 4 
這樣的語法

樣本輸出

3 

-1 

2 

0 

我的代碼:

#include <stdio.h> 

//Datatype Declarations 
typedef int (*arithFuncPtr)(int, int); 


//Function Prototypes 
int add(int x, int y); 


int main() 
{ 
    int a, b, optype, res; 

    arithFuncPtr ptr; 

    //ptr points to the function add 
    ptr = add; 

    scanf("%i %i", &a, &b); 

    res = (*ptr)(a, b); 

    printf("%i\n", res); 

    return 0; 
} 

int add(int x, int y) 
{ 
    return x+y; 
} 
+0

檢查它我將不得不使用if語句。我試圖找到一種方法來檢查哪個運算符沒有if語句。 – CHEWWWWWWWWWW

+2

您如何創建一個函數指針數組,並基於您正在執行的操作調用基於一點創意編制的適當函數? ('op-1',其中'op'是你想要的操作,你的函數指針數組分別包括加法,減法乘法和除法函數地址。) – WhozCraig

回答

4

您可以將函數指針放入數組中。

#include <stdio.h> 

//Datatype Declarations 
typedef int (*arithFuncPtr)(int, int); 


//Function Prototypes 
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 main() 
{ 
    int a, b, optype, res; 

    arithFuncPtr ptr[4]; 

    //ptr points to the function 
    ptr[0] = add; 
    ptr[1] = sub; 
    ptr[2] = mul; 
    ptr[3] = div; 

    scanf("%i %i %i", &a, &b, &optype); 

    res = (ptr[optype - 1])(a, b); 

    printf("%i\n", res); 

    return 0; 
} 

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; 
} 
+0

那麼我可以問一下typedef int(* arithFuncPtr) (int,int);線?顯然這是一項家庭作業:P謝謝你的幫助:) – CHEWWWWWWWWWW

+0

沒關係,我沒看見它在代碼中的用法。謝謝一堆!我實際上已經寫了這個代碼,沒有arithFuncPtr ptr [4]。必須與typedef混淆。不太清楚。 – CHEWWWWWWWWWW

+0

真棒我寫了完全相同的東西。爲了防止出現界限,並且沒有「if」,您可以使用模運算。這裏是[我的版本](https://gist.github.com/CanTheAlmighty/e411590d2a48d2ec9fb1),不值得再作回覆。 – Can