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语句,我该怎么做。
我在想两个可能的解决方案
创建4个三分球和每个指针尊重算术运算,但我还是得做一些输入 验证这需要如果或开关语句
这不是一个真正的解决方案,但基本的想法可能会像。如果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;
}
检查它我将不得不使用if语句。我试图找到一种方法来检查哪个运算符没有if语句。 – CHEWWWWWWWWWW
您如何创建一个函数指针数组,并基于您正在执行的操作调用基于一点创意编制的适当函数? ('op-1',其中'op'是你想要的操作,你的函数指针数组分别包括加法,减法乘法和除法函数地址。) – WhozCraig