6

C语言简易计算器的两种方法_编程小白的技术博客_51CTO博客

 1 year ago
source link: https://blog.51cto.com/u_15922371/5986917
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

C语言简易计算器的两种方法

精选 原创

海绵饱饱q 2023-01-03 23:24:54 博主文章分类:C语言 ©著作权

文章标签 #include 数组元素 数据 文章分类 C/C++ 编程语言 yyds干货盘点 阅读数186

第一种方法   函数指针数组

#include<stdio.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 div(int x,int y)
{
return x/y;
}

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

int main()
{
int x=0;
int y=0;
int input=0;
int (*pf[5])(int,int)={0,add,sub,mul,div};//数组元素个数可以不写

do
{
menu();
printf("请输入:>\n");
scanf("%d",&input);
if(input>=1 && input<=4)
{
printf("请输入数据:>\n");
scanf("%d%d",&x,&y);
printf("%d\n",pf[input](x,y));

}

else if(input==0)
{
printf("退出\n");
break;
}

else
{
printf("输入错误\n");
break;
}
}while(input);
return 0;
}

第二种方法   switch case语句

#include<stdio.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 div(int x,int y)
{
return x/y;
}

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

void calc(int (*pf)(int,int))
{
int x=0;
int y=0;
printf("请输入:>");
scanf("%d%d",&x,&y);
printf("%d\n",pf(x,y));
}

int main()
{
int x=0;
int y=0;
int input=0;
do
{
menu();
printf("请输入:>");
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);
}
  • 收藏
  • 评论
  • 分享
  • 举报

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK