【发布时间】:2015-11-30 03:44:41
【问题描述】:
所以..我知道如果我将(*ptr) 作为某个函数 f 那么
res = (*ptr)(a,b) is the same as res = f(a,b).
所以现在我的问题是我必须读入 3 个整数。前 2 个是操作数,第三个是运算符,例如1 = add, 2 = subtract, 3 = multiply, 4 = divide。如果没有 if 或 switch 语句,我该怎么做。
我在考虑两种可能的解决方案
创建 4 个指针并将每个指针引用到算术运算,但是我仍然需要进行某种输入 需要 if 或 switch 语句的验证
这不是一个真正的解决方案,但基本想法可能会像这样。如果 c = 运算符,那么我可以以某种方式执行 res = (*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 语句。
-
您如何创建一个函数指针数组并根据您正在执行的操作调用适当的函数索引? (
op-1,其中op是您想要的操作,您的函数指针数组分别包括加、减乘和除函数地址。)
标签: c math function-pointers arithmetic-expressions