c - 随机词生成器中的奇怪输出
问题描述
我在以下程序的输出中遇到了一些问题。该程序随机生成单词,首先是随机辅音,然后是随机元音,然后再次生成您想要的最大字母数。
当我打印生成后立即生成的单词时,它会按预期给我一个单词列表。当我退出单词生成和堆叠循环并再次打印单词的输出时,我将所有单词混合成一个长链,这真的很奇怪。怎么了?
#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
解决方案
这是因为 is 以连续方式存储,没有任何空字符。
方法1:如果你只是想正确打印它,你可以通过写下面的行来做到:
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++ - 从 lineEdit QT 获取 unicode 并将其写入文件
- spotfire - 对于满足特定条件的值,同一列中的行之间的差异
- python - python - html - 如何更改标签关闭部分的位置/移动整个部分
- javascript - 为什么按钮中的 th:attr 没有发送正确的数据?
- javascript - 在 Angular 6 中使用 ngClass 有条件地应用通用类名
- javascript - JQM 日历显示多个月份
- java - 我如何只注入一个地图
- c++-winrt - C++/winRT xaml 键盘事件处理程序
- linq - 即使表不返回匹配项,Linq 从多个连接中选择并返回所有行
- javascript - 发出 AJAX 请求的问题