C 语言函数指针示例:使用函数指针执行最大值、最小值、加法和减法运算
修改后的代码如下所示:
#include <stdio.h> // 修改为#include <stdio.h>
int max(int x, int y)
{
int temp;
if (x > y)
temp = x;
else
temp = y;
return temp;
}
int min(int x, int y)
{
int temp;
if (x < y)
temp = x;
else
temp = y;
return temp;
}
int add(int x, int y)
{
return x + y;
}
int sub(int x, int y)
{
return x - y;
}
int pr(int (*p)(int, int), int x, int y)
{
int ret;
ret = (*p)(x, y);
return ret;
}
int main()
{
int (*p[4])(int, int) = {max, min, add, sub};
int num;
num = (*p[2])(5, 8);
printf("%d\n", num);
int number;
int m, n;
int choice; // 修改变量类型为int
printf("please input the numbers and the function\n");
scanf("%d,%d,%d", &choice, &m, &n); // 修改为%d
number = pr(p[choice], m, n);
printf("number=%d\n", number);
return 0;
}
主要的修改包括:
- 将
#include"./stdio.h"修改为#include <stdio.h>,使用尖括号来包含标准头文件。 - 将
char* k修改为int choice,因为读取的是数字而不是字符串。 - 将
scanf("%s, %d, %d", &k, &m, &n)修改为scanf("%d,%d,%d", &choice, &m, &n),将逗号去除,并修正变量类型。 - 将
pr(k, m, n)修改为pr(p[choice], m, n),传入选择的函数指针。 - 修改
printf中的格式控制符为%d,以匹配整数类型的数据。
这样修改后的代码应该能正确运行。
原文地址: http://www.cveoy.top/t/topic/bT6z 著作权归作者所有。请勿转载和采集!