我正在尝试构建一个单词猜测器,您可以从给定的选项中猜测一个单词。单词存储在一个数组中。尽管他们必须赢,但球员还是输了。
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void guess(int N) {
int number, guess, numberofguess = 0;
int myval[] = {"R22", "B3", "R33", "B232", "R12",
"B45", "R2", "B12", "R45", "B32"};
srand(time(NULL));
number = rand() % N;
printf("choose a number "
"{'R22','B3','R33','B232','R12','B45','R2','B12','R45','B32'}n");
char str[20];
gets(str);
printf("your guess is %sn", str);
if (str == myval[number]) {
printf("you winn");
} else
printf("you losen");
printf("the number is %s", myval[number]);
}
main() {
int N = 9;
guess(N);
return 0;
}
当玩家输入代码并与随机输出匹配时,我想以这样的方式编写代码——if语句有效。
- 在比较C中的字符串时使用strcmp
- 从字符串创建数组时,应该将其创建为char*
- 使用
gets
不是一种好的做法 - 您应该指定所有函数的返回类型,包括应返回
int
的main()
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
void guess(int N) {
int number, guess, numberofguess = 0;
const char* myval[] = {"R22", "B3", "R33", "B232", "R12",
"B45", "R2", "B12", "R45", "B32"};
srand(time(NULL));
number = rand() % N;
printf("choose a number "
"{'R22','B3','R33','B232','R12','B45','R2','B12','R45','B32'}n");
char str[20];
gets(str);
printf("your guess is %sn", str);
if (strcmp(str,myval[number]) == 0) {
printf("you winn");
} else
printf("you losen");
printf("the number is %s", myval[number]);
}
int main() {
int N = 9;
guess(N);
return 0;
}