我是编程的新手。
我在C编程语言(K& R)练习1-13的解决方案代码中有6个问题。任务是编写一个打印单词长度直方图的程序。如图所示。
我已粘贴下面的代码以及我为帮助我理解所做的笔记。
我的问题紧挨着我有疑问的代码的各个部分。提前谢谢!
int main () { int c, i, nc, state; int len; /* length of each bar */ int maxvalue; /* maximum value for wl[] */ int ovflow; /* number of overflow words */ int wl[MAXWORD]; /* word length counters. Defining an int array with 11 character variables. This is the same as saying int wl[11] */ state = OUT; nc = 0; /* number of chars in a word */ ovflow = 0; /* number of words */
for (i = 0; i < MAXWORD; ++i) wl[i] = 0; while ((c = getchar()) != EOF) //get a character { if (c == ' ' || c == '\n' || c == '\t') // if c is a blank, new line or tab { state = OUT; // we are outside a word.
(nc > 0)
虽然上面声明了nc,nc
如何更改?就像用户如何改变它一样? nc
的输入在哪里?if (nc > 0) if (nc < MAXWORD) //if the number of characters is less than the maxword length counter. { ++wl[nc]; // increase the number of elements/number of characters in the array by 1. }
++wl[nc]
中的增量运算符增加1?它会增加数组wl
吗? nc
中++wl[nc]
的重要性是什么?
else { ++ovflow; // if nc is greater than the maxword however, increase the overflow by 1 } nc = 0; }
上面,nc = 0
是否会重置字符数?
// The beginning of a new word else if (state == OUT) { //if state is out or better put, if we are not in a word state = IN; // In that case, upon accepting a new character, we are at the start of a new word hence state is in. nc = 1; // and upon accepting a character, the number of characters is 1. } // inside a word else { ++nc; // if not outside a word or in a word, increase the number of characters by 1 } }
我们在下面的行中初始化maxvalue
?
maxvalue = 0 ; for (i = 1; i < MAXWORD; ++i) //Run a for loop until i is 10. Since MAXWORD length counter is 11. { if (wl[i] > maxvalue) //if the elements in the array is greater than the max number of elements allowed in the array maxvalue = wl[i]; //the max amount of elements allowed in the array is the same as the number of elements in the array. }
我没有得到这部分代码。有人可以向我解释一下吗?
for (i = 1; i < MAXWORD; ++i) { printf("%5d - %5d : ", i, wl[i]); //i refers to the word length while wl[i] is the frequency of its occurence. if (wl[i] > 0) { if ((len = wl[i] * MAXHIST / maxvalue) <= 0) len = 1; } else len = 0; while (len > 0) { putchar ('*'); --len; } putchar('\n'); } if (ovflow > 0) printf("There are %d words >= %d\n", ovflow, MAXWORD);
答案 0 :(得分:4)
已在else if (state == OUT)
nc'th
数组中的wl
元素递增(array [1]是数组中的第二个元素,因此第n个元素实际上是nc + 1。 ..)
如果特定单词的长度大于0 len则获取值wl[i] * MAXHIST / maxvalue
然后检查为0.如果它等于0则len变为1。
否则:len变为1
毕竟这个程序打印len
次&#39; *&#39;然后是换行符