鱼C论坛

 找回密码
 立即注册
查看: 378|回复: 3

程序求助

[复制链接]
发表于 2025-11-15 21:57:12 | 显示全部楼层
问题分析:
您的代码中,process 函数需要使用函数指针来实现多态行为。但当前声明 int(*fun)() 不正确,因为它不匹配 maxminadd 函数的实际参数(它们都需要两个 int 参数)。这会导致编译错误。

修正建议:
1. 将 process 的函数指针参数改为 int (*fun)(int, int)
2. 实现 process 函数,使其调用传入的函数指针并打印结果。
3. 补充定义 minadd 函数。

以下是修正后的完整代码示例:


  1. #include <stdio.h>

  2. // 声明函数
  3. int max(int, int);
  4. int min(int, int);
  5. int add(int, int);
  6. void process(int x, int y, int (*fun)(int, int));

  7. int main() // 建议使用 int main() 代替 void main()
  8. {
  9.     int a, b;
  10.     printf("Enter a and b:");
  11.     scanf("%d %d", &a, &b);

  12.     printf("max=");
  13.     process(a, b, max);

  14.     printf("min=");
  15.     process(a, b, min);

  16.     printf("sum=");
  17.     process(a, b, add);

  18.     return 0; // 如果使用 int main()
  19. }

  20. // 实现 process 函数
  21. void process(int x, int y, int (*fun)(int, int)) {
  22.     int result = fun(x, y);
  23.     printf("%d\n", result);
  24. }

  25. // 您的 max 函数
  26. int max(int x, int y) {
  27.     int z;
  28.     if (x > y) {
  29.         z = x;
  30.     } else {
  31.         z = y;
  32.     }
  33.     return z;
  34. }

  35. // 补充 min 函数
  36. int min(int x, int y) {
  37.     return (x < y) ? x : y;
  38. }

  39. // 补充 add 函数
  40. int add(int x, int y) {
  41.     return x + y;
  42. }
复制代码


关键点说明:
- process 函数通过函数指针 fun 调用不同的函数(如 max、min、add),实现“多态”效果。
- 确保所有函数在调用前正确定义或声明。
- 如果使用 void main() 编译不通过,请改为 int main() 并添加 return 0;

如果还有疑问,请继续提出!

以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2026-4-1 21:33

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表