[英]random characters in c
我編寫了一個程序,試圖通過隨機選擇字符來“猜測”一個單詞。 但是,我的程序正在打印不在字符列表中的字符。 這里發生了什么?
#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"
),並以'\\0'
字符結尾(因此,字符總數實際上為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] = '\0';
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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.