2015-09-04 94 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