C语言运用回调函数实现计算器

Pandora ·
更新时间:2024-09-20
· 77 次阅读

本文实例为大家分享了C语言运用回调函数实现计算器的具体代码,供大家参考,具体内容如下

回调函数概念:

回调函数是一个通过函数指针调用的函数,也就是将函数的地址作为参数传递给另一个函数,当这个指针回来调用其指向的函数时,称为回调函数。

本次制作计算器的功能:

1.add —— 加法

2.sub —— 减法

3.mul —— 乘法

4.div —— 除法

0.exit —— 退出

具体来通过代码讲解:

(1)首先写一个菜单函数,在运行程序时打印菜单

void menu() { printf("*************************\n"); printf("******* 1.add *******\n"); printf("******* 2.sub *******\n"); printf("******* 3.mul *******\n"); printf("******* 4.div *******\n"); printf("******* 0.exit *******\n"); printf("*************************\n"); }

(2)写好四个关于加、减、乘、除操作的函数

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; }

(3)写主函数,定义input是你要输入的数,用来选择计算器的功能;然后使用do while循环,内嵌菜单函数。

int main() { int input = 0; do { menu(); printf("请选择你要进行的操作:\n"); scanf("%d",&input); } while (input); return 0; }

(4)用switch语句定义每个数字相对应的功能;default代表其他选项;Calc函数是我们接下来要写的回调函数。

int main() { int input = 0; do { menu(); printf("请选择你要进行的操作:\n"); scanf("%d",&input); switch (input) { case 1: Calc(Add); break; case 2: Calc(Sub); break; case 3: Calc(Mul); break; case 4: Calc(Div); break; case 0: printf("退出计算器\n"); break; default: printf("选择错误,请重新选择!\n"); break; } } while (input); return 0; }

(5)定义Calc函数,用一个函数指针作为参数接收(Add、Sub、Mul、Div)函数的地址;pf作为函数指针直接指向相应函数;然后输出结果;(这个回调函数csdn似乎识别不了,编译器是可以的,所以就以注释的形式写了,后面也是一样)。

void Calc() //括号内容:int(*pf)(int, int) { int x = 0; int y = 0; int ret = 0; printf("请输入2个操作数:\n"); scanf("%d %d",&x,&y); ret = pf(x,y); printf("%d\n",ret); }

最后送上全部的代码小小总计一下:

#include <stdio.h> void menu() { printf("*************************\n"); printf("******* 1.add *******\n"); printf("******* 2.sub *******\n"); printf("******* 3.mul *******\n"); printf("******* 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; } void Calc() //括号内容:int(*pf)(int, int) { int x = 0; int y = 0; int ret = 0; printf("请输入2个操作数:\n"); scanf("%d %d",&x,&y); ret = pf(x, y); printf("%d\n", ret); } int main() { int input = 0; do { menu(); printf("请选择你要进行的操作:\n"); scanf("%d",&input); switch (input) { case 1: Calc(Add); break; case 2: Calc(Sub); break; case 3: Calc(Mul); break; case 4: Calc(Div); break; case 0: printf("退出计算器\n"); break; default: printf("选择错误,请重新选择!\n"); break; } } while (input); return 0; }



回调 函数 C语言 回调函数

需要 登录 后方可回复, 如果你还没有账号请 注册新账号