Mathbox软件,有两个子命令:calc和exam calc子命令类似于计算器,给定计算符(-s add/sub/mul/div)和参数(-o/-p)然后输出算式和结果。 exam子命令为计算机出题(10以内的加减法),然后用户作答,答对打错给出结论,并给出用户计算所用的时间。
```c #include<stdio.h> #include<stdlib.h> #include <getopt.h> #include <string.h> #include <time.h> //命令格式: ./Mathbox calc -s add/sub/mul/div -o x -p y // ./Mathbox exam static const char short_opts[] = "s:o:p:e"; clock_t start, stop; double duration; static int add (int x, int y) { printf ("%d + %d = %d\n", x, y, x+y); return 0; } static int sub (int x, int y) { printf ("%d - %d = %d\n", x, y, x-y); return 0; } static int mul (int x, int y) { printf ("%d * %d = %d\n", x, y, x*y); return 0; } static int d (int x, int y) { if(y!=0) { printf ("%d / %d = %d\n", x, y, x/y); } else printf("Divisor can not Be zero!!"); return 0; } int main(int argc, char *argv[]) { int a,b,an,r,myan; char c,s[10]; int x,y; if ( argc <=1 ) { printf ("Use sub-command!\n"); return 1; } if ( strcmp (argv[1], "calc") == 0 ) { while ( (c = getopt (argc, argv, short_opts)) != -1 ) { switch ( c ) { case 's': strcpy(s,optarg); break; case 'p': y=atoi(optarg); break; case 'o': x=atoi(optarg); break; } } if ( strcmp (s, "add") == 0 ) { add (x, y ); } else if ( strcmp (s, "sub") == 0 ) { sub (x, y ); } else if ( strcmp (s, "mul") == 0 ) { mul (x, y); } else if ( strcmp (s, "div") == 0 ) { d (x, y ); } else { printf ("ERROR: Unknown sub-command!\n"); return 2; } } if ( strcmp (argv[1], "exam") == 0 ) { srand((unsigned)time(NULL)); a=rand()%10+1; b=rand()%10+1; r=rand()%10+1; if(r>5)//随机加法或加法 { printf("%d + %d= ?\n",a,b); an=a+b; printf("you answer:"); time(&start); scanf("%d",&myan); time(&stop); duration=(double)(stop-start); if(myan==an) { printf("Correct answer!!\n"); printf("Time:%f s",duration); } else { printf("Wrong!!\n"); printf("Time:%f s\n",duration); } } else if(r<=5) { printf("%d - %d= ?\n",a,b); an=a-b; printf("you answer:"); time(&start); scanf("%d",&myan); time(&stop); duration=(double)(stop-start); if(myan==an) { printf("Correct answer!!\n"); printf("Time:%f s",duration); } else { printf("Wrong!!\n"); printf("Time:%f s\n",duration); } } } return 0; }