gpt4 book ai didi

c - 使用函数代替运算符

转载 作者:太空宇宙 更新时间:2023-11-04 01:00:44 28 4
gpt4 key购买 nike

所以我正在尝试制作一个基于用户输入进行数学运算的程序,但是我在尝试根据他们提供的内容设置数学运算符时遇到了问题。

功能:

const operator(int val)
{
if (val == 1)
{
return +;
}
if (val == 2)
{
return -;
}
}

主要代码看起来像这样

scanf("%d", val)
output = 4 operator(val) 2
printf("%d", output)

有没有我可以用来代替运算符的变量类型?如果没有,是否有办法使变量/函数引用成为已定义的宏?

例如:

#define plus +

然后在代码中引用宏?

最后我知道我可以为每个输入设置 if 案例,但是对于类似的东西,这很难扩展,

output = 2 operator(val) 5 operator(val) 7 operator(val) 3 

我认为这需要 64 个 if 语句才能使其工作。

感谢您的阅读,我对此束手无策。

最佳答案

你可以做的是使用函数指针。

假设您将自己限制为整数并为此示例添加/减去:

int add(int a, int b)
{
return a + b;
}

int subtract(int a, int b)
{
return a - b;
}

// without typedef, the signature of get_operator would be really messy
typedef int (*arithmetic_func)(int,int);

arithmetic_func get_operator(int val)
{
if (val == 1)
{
return &add;
}
if (val == 2)
{
return &subtract;
}
return NULL; // what to do if no function matches?
}

代替 output = 4 operator(val) 2 你可以这样写:

output = get_operator(val)(4, 2)

发生的事情是,get_operator(val) 函数调用返回一个指向实际算术函数的函数指针。然后以 (4, 2) 作为参数调用这个实际的算术函数。

关于c - 使用函数代替运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40649601/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com