c中的随机字符

random characters in c

我编写了一个程序,试图通过随机选择字符来 "guess" 一个单词。但是,我的程序正在打印不在我的字符列表中的字符。这是怎么回事?

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>

int main(){

    int index, i;
    time_t t;
    char characters[] = "bdefgir";
    char word[] = "friedberg";
    srand((unsigned)time(&t));
    char result[9] = {0};

    while(strcmp(result, word) != 0){

        for (i = 0; i < 9; i++) {
            index = rand() % 8;
            result[i] = characters[index];
        }
        printf("Result:\t%s\n", result);

    }

    return 0;

}

你拼错的变量 wort 应该是 word。此外,您还必须有包含 9 个字符的 result 数组(如您的单词 "friedberg")并以 '[=15=]' 字符结尾(因此字符总数实际上是 10)。

正确的解决方案是:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>

int main() {

    int index, i;
    time_t t;
    char characters[] = "bdefirg";

    char word[] = "friedberg";

    srand((unsigned) time(&t));
    char result[10];
    result[9] = '[=10=]';

    while (strcmp(result, word) != 0) {

        for (i = 0; i < 9; i++) {
            index = rand() % 7;
            result[i] = characters[index];
        }
        printf("Result:\t%s\n", result);

    }

    return 0;

}