This commit is contained in:
hairrrrr
2020-04-10 17:56:09 +08:00
parent c5fdb003da
commit f7a471e3f4
2 changed files with 48 additions and 0 deletions

View File

@@ -0,0 +1,27 @@
#include<stdio.h>
#include<string.h>
#define NUM_PLANETS 9
int main(int argc, char* argv[]) {
int i, j;
char* planets[NUM_PLANETS] = {
"Mercury", "Venus", "Earth",
"Mars", "Jupiter", "Saturn",
"Uranus", "Neptune", "Pluto"
};
for (i = 1; i < argc; i++) {
for (j = 0; j < NUM_PLANETS; j++)
if (strcmp(argv[i], planets[j]) == 0) {
printf("%s is a planet %d\n", argv[i], j + 1);
break;
}
if (j == NUM_PLANETS)
printf("%s is not a planet\n", argv[i]);
}
return 0;
}
// 程序会依次访问每个命令行参数,把它与 planets 中的字符串进行比较,直到找到匹配的名字或到了数组末尾才停止。

View File

@@ -0,0 +1,21 @@
#### 程序:核对行星的名字
设计一个程序检查一系列字符串,从而找出那些字符串是行星的名字。执行程序时,用户把待测试的字符串放置在命令行中:
```c
planet Mercury Aotoman Pluto Thebug Earth
```
程序会指出每个字符串是否为行星名。如果是,程序还将显示行星的编号:
```c
Mercury is a planet 1
Aotoman is not a planet
Pluto is a planet 9
Thebug is not a planet
Earth is a planet 3
```
**注意:**命令行输入的第一个参数 planet 是 c 程序编译出的可执行程序名。一般一个叫 x.c 的程序编译后的可执行程序就叫做 x 。
我们命名这个 c 程序为 planet.c 所以编译后的可执行文件应该叫做 planet (在 Windows 上后缀应该为 .exe