以下程序利用指向函数的指针实现函数调用,完成可选择的加减乘除运算。
#include “stdio.h”
/*定义函数add*/
int add(int x,int y)
{ printf(“%d+%d=”,x,y);return x+y;}
/*定义函数sub*/
int sub(int x,int y)
{printf(“%d-%d=”,x,y);return x-y;}
/*定义函数mult*/
int mult(int x,int y)
{ printf(“%d*%d=”,x,y);return x*y;}
/*定义函数dev*/
int dev(int x,int y)
{ printf(“%d/%d=”,x,y);return x/y;}
void main()
{ int (*fp)(int,int);
char op;
int x,y;
printf(“Please intput the expression a +(-*/)b:\n”);
scanf(“%d”,&x);
scanf(“%c”,&op);
scanf(“%d”,&y);
① (op)
{case ‘+’: fp= ② ;break;
case ‘-‘: fp=sub; break;
case ‘*’: fp=mult; break;
case ‘/’: fp=dev; break;
default: printf(“Operator is illegal;\n”);
}
printf(“%d\n”, ③ (x,y));
}
#include “stdio.h”
#include “conio.h”
/*定义函数add*/
int add(int x,int y)
{ printf(“%d+%d=”,x,y);return x+y;}
/*定义函数sub*/
int sub(int x,int y)
{printf(“%d-%d=”,x,y);return x-y;}
/*定义函数mult*/
int mult(int x,int y)
{ printf(“%d*%d=”,x,y);return x*y;}
/*定义函数dev*/
int dev(int x,int y)
{ printf(“%d/%d=”,x,y);return x/y;}
void main()
{ int (*fp)(int,int);
char op;
int x,y;
printf(“Please intput the expression a +(-*/)b:\n”);
scanf(“%d”,&x);
scanf(“%c”,&op);
scanf(“%d”,&y);
switch (op)
{case ‘+’: fp= add ;break;
case ‘-‘: fp=sub; break;
case ‘*’: fp=mult; break;
case ‘/’: fp=dev; break;
default: printf(“Operator is illegal;\n”);
}
printf(“%d\n”, fp(x,y));
getch();
}
程序的执行结果是
第一次:
Please intput the expression a +(-*/)b:
12+5
12+5=17
第二次:
Please intput the expression a +(-*/)b:
23/15
23/15=1
暂无评论内容