【问题标题】:How do i perform arithmetic operations with function pointers?如何使用函数指针执行算术运算?
【发布时间】: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 语句,我该怎么做。

我在考虑两种可能的解决方案

  1. 创建 4 个指针并将每个指针引用到算术运算,但是我仍然需要进行某种输入 需要 if 或 switch 语句的验证

  2. 这不是一个真正的解决方案,但基本想法可能会像这样。如果 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


【解决方案1】:

你可以把你的函数指针放在一个数组中。

#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;
}  

【讨论】:

  • 那么请问 typedef int(*arithFuncPtr)(int, int); 的意义何在?线?显然这是一个家庭作业:P 感谢您的帮助 :)
  • 好吧,没关系,我在代码中看到了它的用法。非常感谢!实际上,我已经在没有 arithFuncPtr ptr[4] 的情况下编写了这段代码。一定与 typedef 混淆了。不太清楚。
  • 太棒了,我写了完全相同的东西。为了防止越界,并且没有ifs,您可以使用模运算。这里是my version,不值得再回复。
猜你喜欢
  • 2015-12-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-01-08
  • 2021-05-12
  • 2014-04-26
  • 2014-11-13
相关资源
最近更新 更多