教小朋友寫程序。設計一個:設計
./calc + 3 4 程序輸出 3+4 = 7string
支持四中運算,+,-,*,/io
但輸入:./calc * 5 6擴展
Usage: hello op a b, op:[+,-,*,/]
argc:6
./calc,a.txt,calc,hello.c,5,6,gc
並非5個參數,而是六個參數。 * 被擴展成a.txt, calc,hello.c。這個Shell設計,*表明當前目錄下的任何文件。程序
要想正確調用,得寫作 ./calc '*' 5 6di
#include <stdio.h>
#include <stdlib.h>
#include <string.h>文件
int add(int a, int b) {
return a + b;
}vi
int sub(int a, int b) {
return a - b;
}co
int mul(int a, int b) {
return a * b;
}
int divi(int a, int b) {
return a / b;
}
int main(int argc, char* argv[]) {
int a,b,c;
const char* op;
printf("Hello,world\n");
if (argc != 4) {
int i;
printf("Usage: hello op a b, op:[+,-,*,/]\n");
printf("argc:%d\n",argc);
for (i = 0; i < argc; i++) {
printf("%s\n", argv[i]);
}
return 0;
}
op = argv[1]; a = atoi(argv[2]); b = atoi(argv[3]); if (strcmp(op,"+") == 0) { c = add(a,b); printf("%d+%d=%d\n", a, b, c); } else if (strcmp(op, "-") == 0) { c = sub(a,b); printf("%d-%d=%d\n", a, b, c); } else if (strcmp(op, "x") == 0) { c = mul(a,b); printf("%d*%d=%d\n", a, b, c); } else if (strcmp(op, "/") == 0) { c = divi(a,b); printf("%d/%d=%d\n", a, b, c); } return 0; }