gpt4 book ai didi

c - 随机词生成器中的奇怪输出

转载 作者:太空宇宙 更新时间:2023-11-04 05:15:54 26 4
gpt4 key购买 nike

我在以下程序的输出中遇到了一些问题。该程序随机生成单词,首先是一个随机辅音,然后是一个随机元音,然后再次生成您想要的最大字母数。

当我在生成后立即打印生成的单词时,它会按预期给我一个单词列表。当我跳出单词生成和堆叠循环,并再次打印单词输出时,我将所有单词混合在一个长链中,这真的很奇怪。怎么了?

#include <stdio.h>

#define MAXWORDS 10
#define MAXLETTERS 6

int lcg(int Xcur) /*linear congruential generator*/
{
int A = 445, C = 700001, M = 2097152;
int Xnext = (A * Xcur + C) % M;
return Xnext;
}

int main()
{
int x;
printf("input seed for linear congruential generator: ");
scanf("%d",&x);

char consonants[]="bcdfghjklmnprstvwxz";
char vowels[]="aeiou";

int i,j;
int turn;

char words[MAXWORDS][MAXLETTERS];

for(i=0;i<MAXWORDS;i++)
{
turn=1;

for(j=0;j<MAXLETTERS;j++,turn++)
{
x=lcg(x); /* random number generated */

if(turn%2) /* one consonant, one vowel, in turn */
words[i][j]=consonants[x%19];
else
words[i][j]=vowels[x%5];
}

words[i][j]='\0';

/* print each word generated */
printf("word %d: %s\n", i+1, words[i]);
}

/* print the first word again */
printf("\n\nthe 1st word again: %s\n",words[0]);

return 0;
}

输出:

input seed for linear congruential generator: 23
word 1: wuduca
word 2: navozo
word 3: depiza
word 4: jukiti
word 5: raliwi
word 6: danila
word 7: cexewi
word 8: bamohu
word 9: jiruzi
word 10: temomo


the 1st word again: wuducanavozodepizajukitiraliwidanilacexewibamohujiruzitemomo

最佳答案

这是因为它是以连续的方式存储的,没有任何空字符。

方法一:如果你只是想正确地打印它,你可以通过写在下面一行来完成:

printf("\n\nthe 1st word again: %s\n",words[0]);

作为

printf("\n\nthe 1st word again: %.*s\n",MAXLETTERS, words[0]);

方法二:

声明单词为

char words[MAXWORDS][MAXLETTERS+1];

并将里面的for循环写成

for(j=0;j<MAXLETTERS;j++,turn++)
{
x=lcg(x); /* random number generated */

if(turn%2) /* one consonant, one vowel, in turn */
words[i][j]=consonants[x%19];
else
words[i][j]=vowels[x%5];
}
words[i][MAXLETTERS] = '\0';

关于c - 随机词生成器中的奇怪输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57920729/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com