#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
void menu()
{
printf("*****************************\n");
printf("****1.Add*******2.Sub********\n");
printf("****3.Mul*******4.Div********\n");
printf("***********0.exit************\n");
printf("*****************************\n");
}
int Add(int x, int y)
{
return x + y;
}
int Sub(int x, int y)
{
return x - y;
}
int Mul(int x, int y)
{
return x * y;
}
int Div(int x, int y)
{
return x / y;
}
int cal(int (*p)(int,int))//此处用函数指针接收,p指向地址即为Add(),Sub(),Mul(),Div()函数的地址
{
int x=0;
int y=0;
printf("请输入2个操作数:>");
scanf("%d %d", &x, &y);
return p(x, y);
}
int main()
{
int input = 0;
do
{
menu();
int ret = 0;
printf("请选择:>\n");
scanf("%d", &input);
switch (input)
{
case 1:
ret = cal(Add);//此处往cal中传的是Add函数的地址,故应用函数指针接收
printf("ret=%d\n", ret);
break;
case 2:
ret = cal(Sub);
printf("ret=%d\n", ret);
break;
case 3:
ret = cal(Mul);
printf("ret=%d\n", ret);
break;
case 4:
ret = cal(Div);
printf("ret=%d\n", ret);
break;
case 0:
printf("退出程序\n");
break;
default:
printf("选择错误,请重新选择:>");
}
} while (input);
return 0;
}
使用c语言实现计算器
于 2023-08-25 22:48:36 首次发布