|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
/*******************************************************/
/*设一个函数process,在调用它的时候,每次实现不同的功能*/
/*输入a和b两个数,第一次调用process时找出a和b中大者,第*/
/*二次找出其中小者,第三次求a与b之和。 */
/*******************************************************/
#include <stdio.h>
void main()
{
int max(int, int);
int min(int, int);
int add(int, int);
void process(int x, int y, int(*fun)());
int a, b;
printf("Endter a and b:");
scanf("%d %d", &a, &b);
printf("max = ");
process(a, b, max);
printf("min = ");
process(a, b, min);
printf("sun = ");
process(a, b, add);
}
int max(int x, int y)
{
int z;
if(x > y)
{
z = x;
}
else
{
z = y;
}
return z;
}
int min(int x, int y)
{
int z;
if(x < y)
{
z = x;
}
else
{
z = y;
}
return z;
}
int add(int x, int y)
{
int z;
z = x + y;
return z;
}
void process( int x, int y, int(*fun)() )
{
int result;
result = (*fun)(x,y);
printf("%d\n", result);
}
错误指令:
E:\编程\C例子\26process.cpp(20) : error C2664: 'process' : cannot convert parameter 3 from 'int (int,int)' to 'int (__cdecl *)(void)'
None of the functions with this name in scope match the target type
E:\编程\C例子\26process.cpp(22) : error C2664: 'process' : cannot convert parameter 3 from 'int (int,int)' to 'int (__cdecl *)(void)'
None of the functions with this name in scope match the target type
E:\编程\C例子\26process.cpp(24) : error C2664: 'process' : cannot convert parameter 3 from 'int (int,int)' to 'int (__cdecl *)(void)'
None of the functions with this name in scope match the target type
E:\编程\C例子\26process.cpp(62) : error C2197: 'int (__cdecl *)(void)' : too many actual parameters
本帖最后由 claws0n 于 2018-8-27 17:36 编辑
楼主,修改了,.cpp 也适用。函数的声明最好是在 main() 外面 #include <stdio.h>
int max(int, int);
int min(int, int);
int add(int, int);
void process(int x, int y, int(*fun)(int, int)); // 带参数的函数
int main()
{
int a, b;
printf("Enter a and b:");
scanf_s("%d %d", &a, &b);
printf("max = ");
process(a, b, max);
printf("min = ");
process(a, b, min);
printf("sum = ");
process(a, b, add);
return 0;
}
int max(int x, int y)
{
if (x > y)
{
return x;
}
else
{
return y;
}
}
int min(int x, int y)
{
if (x < y)
{
return x;
}
else
{
return y;
}
}
int add(int x, int y)
{
return x + y;
}
void process(int x, int y, int(*fun)(int, int)) // 带参数的函数
{
printf("%d\n", (*fun)(x, y)); // 带参数的函数
}
|
|