所以..我明白如果我将(*ptr
)作为某个函数f那么
res = (*ptr)(a,b) is the same as res = f(a,b).
所以现在我的问题是我必须读入 3 个整数。前 2 个是操作数,第三个是运算符,例如1 = 加法,2 = 减法,3 = 乘法,4 = 除法
。如果没有 if 或 switch 语句,我该如何做到这一点。
我正在考虑两种可能的解决方案
create 4 pointers and deference each pointer to an arithmetic operation, but with that I still have to do some sort of input validation which would require if or switch statements
This isn't really a solution but the basic idea would probably by like. if c = operator then I can somehow do something like res = (*ptrc)(a,b) but I don't think there's such a syntax for 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;
}
最佳答案
您可以将函数指针放入数组中。
#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;
}
关于c - 如何使用函数指针执行算术运算?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32390328/