c语言用 switch 开关语句实现猜词游戏。
时间: 2023-07-18 11:30:26 浏览: 169
好的,猜词游戏可以这样实现:
首先,我们需要定义一个正确答案,比如:
```c
char answer[] = "apple";
```
然后,我们让用户输入猜测的词,比如:
```c
char guess[100];
printf("Please guess a word: ");
scanf("%s", guess);
```
接下来,我们用 switch 语句来判断用户猜测的词是否正确,比如:
```c
switch (strcmp(guess, answer)) {
case 0:
printf("Congratulations! Your guess is correct!\n");
break;
default:
printf("Sorry, your guess is wrong.\n");
break;
}
```
这里使用了 `strcmp` 函数来比较两个字符串是否相等,如果相等,返回值为 0。
完整代码如下:
```c
#include <stdio.h>
#include <string.h>
int main() {
char answer[] = "apple";
char guess[100];
printf("Please guess a word: ");
scanf("%s", guess);
switch (strcmp(guess, answer)) {
case 0:
printf("Congratulations! Your guess is correct!\n");
break;
default:
printf("Sorry, your guess is wrong.\n");
break;
}
return 0;
}
```
阅读全文