I. Overview of issues
Using C language to implement a simple calculator, can be used to achieve the function of subtraction
noun Explanation:
function pointer: A pointer that is used to point to a function
Array of function pointers: an array containing multiple function pointers
callback function: A function, if the parameter has a function pointer, then this function is the callback function two, problem analysis
This problem can be implemented with Switch,case statement
But here, we're using a bigger method.
Using an array of function pointers
and callback functions
idea:
(1) First write the addition and subtraction multiplier as a function
Note: The type must be the same as the return value
(2) using an array of function pointers, four operation functions are stored in the array
By calling the array, the function is invoked according to the function address Three, code implementation (1) function pointer array code block:
#include <stdio.h>//write four functions of the operation, void Add (int x,int y) {printf ("%d\n", x+y);} void Sub (int x,int y) {printf ("%d\n", XY);} void Mul (int x,int y) {printf ("%d\n", x*y);} void Div (int x,int y) {printf ("%d\n", x/y); ID calculate (int option) {void (*pfun[5]) (int, int) = {0,add,sub,mul,div};//Defines a function pointer array pfun, pointing to the Add,sub,mul,div function int x
= 0;
int y = 0;
printf ("Please enter two operand:>");//Enter operand selection scanf ("%d%d", &x,&y);
if ((option==4) && (y==0))//The selected item is division, and the second operand is 0, the error is {printf ("parameter is incorrect!\n");
return;//Directly returns} Pfun[option] (x,y);//call to function via array of function pointers} void menu ()//Menu function {printf ("1.add 2.sub\n");
printf ("3.mul 4.div\n");
printf ("0.exit\n");
int main () {int option = 0;
while (1) {menu ();
printf ("Please enter:>");
scanf ("%d", &option);
if (option>=1&&option<=4) {calculate (option);
else if (option==0) {break;
else {continue;
} return 0; }
(2) callback function code block:
#include <stdio.h>
void Add (int x,int y)
{
printf ("%d\n", x+y);
}
void Sub (int x,int y)
{
printf ("%d\n", X-y);
}
void Mul (int x,int y)
{
printf ("%d\n", x*y);
}
void Div (int x,int y)
{
printf ("%d\n", x/y);
}
void Calculate (void (*pfun) (int,int))//Because the parameter is a function pointer, so this is a callback function
{
int x = 0;
int y = 0;
printf ("Please enter two operand:>");
scanf ("%d%d", &x,&y);
if ((Pfun==div) && (y==0))
{
printf ("parameter incorrect!\n");
return;
}
Pfun (x,y);//back-pointing function by function pointer
}
void menu ()//Menu function
{
printf (" 1.add 2.sub\n");
printf (" 3.mul 4.div\n");
printf (" 0.exit\n");
}
int main ()
{
void (*pfun[5]) (int, int) = {0,add,sub,mul,div};
int option = 0;
while (1)
{
menu ();
printf ("Please enter:>");
scanf ("%d", &option);
if (option>=1&&option<=4)
{
calculate (pfun[option]);
}
else if (option==0)
{break
;
}
else
{
continue;
}
}
return 0;
}