1. Topic
Use the parameters of the main function to implement an integer calculator. The program can accept three parameters. The first parameter "-a" option performs addition, "-s" option performs subtraction, "-m" option performs multiplication, "-d" option ” option performs division, and the last two arguments are operands.
2. Program code
#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
#include <Windows.h>
#include <stdlib.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;
}
int main(int argc, char* argv[], char* envp[])
{
if (argc != 4)//argc表示的是命令行参数的个数(包含文件名),要求为4个,若输入的不为4个,则输入有误
{
printf("input error!\n");
return 0;
}
int x = atoi(argv[2]);//argv是命令行参数中的每个参数
//aito函数功能是把字符串转成数字,例如atoi('123')结果就为123,要引头文件stdlib.h
int y = atoi(argv[3]);
int ret = 0;
switch (*(argv[1] + 1))//argv取到的是'-'的地址,加一就为后面字母的地址,再解引用
{
case 'a':
ret = Add(x, y);
break;
case 's':
ret = Sub(x, y);
break;
case 'm':
ret = Mul(x, y);
break;
case 'd':
ret = Div(x, y);
break;
}
printf("%d\n", ret);
system("pause");
return 0;
}