- 使用main函数的参数,实现一个整数计算器,程序可以接受三个参数,第一个参数“-a”选项执行加法,“-s”选项执行减法,“-m”选项执行乘法,“-d”选项执行除法,后面两个参数为操作数。
#include <stdio.h> #include <assert.h> #include <string.h> enum JUDGE { RIGHT, ERROR }; int judge = RIGHT; //设定了一个全局变量来区分数字‘0’和非法输入 int _atoi(const char *str,int flag) { int num = 0; assert(str); while(*str) { if((*str<=‘9‘)&&(*str>=‘0‘)) { int charct = flag?1:-1; num = num*10+charct*(*str-‘0‘); if(((charct == 1)&&(num>0x7FFFFFFF)) || ((charct == -1)&&(num<0x80000000))) { num = 0; break; } str++; } else { num = 0; break; } } if(*str == ‘\0‘) { judge = RIGHT; } return num; } int my_atoi(const char *str) { int ret = 0; assert(str); if(*str != ‘\0‘) { int flag = 1; judge = ERROR; if(*str == ‘+‘) { str++; } else if(*str == ‘-‘) { flag = 0; str++; } if(*str != ‘\0‘) { ret = _atoi(str,flag); } } return ret; } int main(int argc,char *argv[]) { int ret = 0; int num1 = my_atoi(argv[2]); //分装了一个自己的函数,将输入的字符串转换成数字 int num2 = my_atoi(argv[3]); char option; if(strcmp(argv[1],"-a") == 0) { option = ‘+‘; ret = (num1) + (num2); } else if(strcmp(argv[1],"-s") == 0) { option = ‘-‘; ret = (num1) - (num2); } else if(strcmp(argv[1],"-m") == 0) { option = ‘*‘; ret = (num1) * (num2); } else if(strcmp(argv[1],"-d") == 0) { option = ‘/‘; ret = (num1) / (num2); } else { printf("输入有误\n"); } printf("(%d) %c (%d) = %d\n",num1,option,num2,ret); return 0; }
main函数的参数形式一般为
int main(int argc,char *argv[])
argv是一个字符串指针数组,里面的首元素*arg[0]一般是文件名,后面的时输入的实参,argc是指参数的个数,包括文件名,所以argc的值不小于1.
时间: 2024-10-07 06:09:08