1。
#include <stdio.h>
#include <assert.h>
#pragma warning (disable:4996)
int my_add(int a,int b)
{
return a + b;
}
int my_sub(int a,int b)
{
return a - b;
}
int my_mul(int a,int b)
{
return a * b;
}
int my_div(int a,int b)
{
if(b == 0)
{
printf("除数不能为0");
return 0;
}
return a / b;
}
int main()
{
int x,y;
int result;
int input=1;
while(input)
{
printf("****************************\n");
printf("****** 1.add 2.sub ******\n");
printf("****** 3.mul 4.div ******\n");
printf("****************************\n");
printf("请选择:");
scanf("%d",&input);
switch(input)
{
case 1:
printf("请输入两个操作数:");
scanf("%d%d",&x,&y);
result = my_add(x,y);
printf("result = %d\n",result);
break;
case 2:
printf("请输入两个操作数:");
scanf("%d%d",&x,&y);
result = my_sub(x,y);
printf("result = %d\n",result);
break;
case 3:
printf("请输入两个操作数:");
scanf("%d%d",&x,&y);
result = my_mul(x,y);
printf("result = %d\n",result);
break;
case 4:
printf("请输入两个操作数:");
scanf("%d%d",&x,&y);
result = my_div(x,y);
break;
default:
printf("选择错误\n");
break;
}
printf("\n");
}
return 0;
}
2。
使用main函数的参数,实现一个整数计算器,程序可以接受三个参数,第一个参数“-a”选项执行加法,“-s”选项执行减法,“-m”选项执行乘法,“-d”选项执行除法,后面两个参数为操作数。
例如:命令行参数输入:test.exe -a 1 2
执行1+2输出3
该代码在Linux下运行
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int my_add(int a,int b)
{
return a + b;
}
int my_sub(int a,int b)
{
return a - b;
}
int my_mul(int a,int b)
{
return a * b;
}
int my_div(int a,int b)
{
if(b == 0)
{
printf("除数不能为0");
return 0;
}
return a / b;
}
void user_guide( char *proc)
{
printf("user guide: \r\n\t%s [-a|-s|-m|-d] data1 data2\n\n",proc);
}
int main(int argc,char *argv[])
{
int ret;
int flag = 0;
int (*ptr[4])(int ,int )={my_add,my_sub,my_mul,my_div};
if(argc !=4 )
{
user_guide(argv[0]);
return 1;
}
if(strcmp(argv[1],"-a")==0)
{
flag = 0;
}else if(strcmp(argv[1],"-s")== 0)
{
flag = 1;
}else if(strcmp(argv[1],"-m")== 0)
{
flag = 2;
}else if(strcmp(argv[1],"-d")== 0)
{
flag = 3;
}else
{
user_guide(argv[0]);
return 1;
}
int x = atoi(argv[2]);
int y = atoi(argv[3]);
ret = (ptr[flag])(x, y);
printf("ret = %d\n",ret);
}