简易计算器:
能够实现加减乘除的功能。
方法一:
函数指针的数组实现:
使⽤函数指针数组的实现:
能够实现加减乘除的功能。
方法一:
函数指针的数组实现:
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
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;
}
static void usage()
{
printf("you enter is error,please again\n");
}
int mydiv(int x, int y)
{
if (y == 0)
{
printf("div data is zero\n");
}
else
{
return x / y;
}
}
int main()
{
int(*p[4])(int, int);//函数指针数组:
p[0] = add;
p[1] = sub;
p[2] = mul;
p[3] = mydiv;
printf("###########################\n");
printf("### 1.add ##### 2.sub #####\n");
printf("### 3.mul #### 4.mudiv ####\n");
printf("### 5.exit ################\n");
while (1)
{
int select = 0;
printf("please select:\n");
scanf("%d", &select);
if (select > 0 && select < 5)
{
int x = 0;
int y = 0;
printf("please enter data<x,y>:\n");
scanf("%d %d", &x, &y);
int ret = p[select - 1](x, y);
printf("%d\n", ret);
}
else if (select == 5)
{
printf("bye bye!");
break;
}
else
{
usage();
}
}
system("pause");
return 0;
}
char *fun1(char*p)
{
printf("%s\n", p);
return p;
}
char *fun2(char*p)
{
printf("%s\n", p);
return p;
}
char *fun3(char*p)
{
printf("%s\n", p);
return p;
}
int main()
{
char*(*pf[3])(char*p);
pf[0] = & fun1;
pf[2] = &fun2;
pf[3] = &fun3;
pf[0] = (fun1);
pf[1] = (fun2);
pf[2] = (fun3);
system("pause");
return 0;
}
方法二:使⽤函数指针数组的实现:
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
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 mydiv(int x, int y)
{
if (y == 0)
{
printf("div data is zero!\n");
}
else
{
return x + y;
}
}
int my_fun(int x, int y, int(*f)(int, int))
{
assert(f);
int ret = (*f)(x, y);
printf("ret %d\n", ret);
}
int main()
{
while (1)
{
printf("##1. add ########## 2. sub########\n");
printf("##3. mul ########## 4.mydiv ######\n");
printf("##5. exit##########################\n");
int sel = 0;
printf("please enter sel:\n");
scanf("%d", &sel);
if (sel<1 || sel>5)
{
printf("your enter is error!please again\n");
continue;//跳出本次循环;
}
if (sel == 5)
{
printf("bye bye!\n");
break;
}
int x = 0;
int y = 0;
printf("please enter <x,y>\n");
scanf("%d %d", &x, &y);
switch (sel)
{
case 1:
my_fun(x, y, add);
break;
case 2:
my_fun(x, y, sub);
break;
case 3:
my_fun(x, y, mul);
break;
case 4:
my_fun(x, y, mydiv);
break;
case 5://eixt
break;
default:
break;
}
}
system("pause");
return 0;
}