【发布时间】:2016-02-10 20:53:00
【问题描述】:
我正在尝试通过创建一个水平方向的直方图来解决 K&R C 练习 1-13,该直方图测量用户输入中不同长度单词的频率。这是我的代码:
#include <stdio.h>
main(){
int a, b, c, d; //array_position, word_length, getchar(), word_count
int y[10]; //array representing word lengths from 1-10 letters
b = 0; //word_length initializes with a zero value
a = 1; //array_position initializes with a value of one (no words contain zero characters)
for(y[a] = 0; (c = getchar()) != EOF;){ //current array position initializes with a zero value, and c initializes as the current input character
if(c != ' ' && c != '\n' && c != '\t') //if c is anything other than a blank, newline or tab
++b; //increment the word_length by one
else //otherwise
++a; //increment the array_position by one
b = 0; //and reset the word_length to zero
}
a = 1; //reset the array_position to one
do{
if(y[a] > 0){ //if current array_position holds a value greater than 0
printf("%i",a); //print the name of the array_position (1,2,3...)
for(d = 0; d < y[a]; ++d){ //reset the word_length--if the word_length is less than the value contained in the current array position, increment the word length by one
putchar('-'); //print a dash and re-evaluate the condition
}
if(d == y[a]){ //when the word_length is equal to the value contained in the current array position
putchar('-'); //print a final dash
putchar('\n'); //and a newline
}
}
++a; //increment the array position by one
}while(a > 11); //repeat until the current array position is 11
}
该代码旨在生成一个非常简单的图表,看起来像这样,对长度为 1-10 个字符的单词进行排序:
1---
2----------
3-----
4--
等等。它还将省略输入中的一个或多个单词未表示的任何长度。但是,上面显示的代码返回 no 输出 at all,我已经为这个问题工作了三天。
我看不到什么阻止了我的代码产生所需的输出?
【问题讨论】:
-
do {...} while(a > 11)应该是for (a=1;a<=10;a++),但是注意数组需要声明为int y[11],这样数组中的有效索引是0到10。并且你需要完全初始化使用它之前的数组。此外,请务必在更新数组之前检查字长是否为<= 10。许多单词的长度超过 10 个字母。 -
循环应该至少打印一次,但在第一次遇到
while (a > 11)时停止。您确定它不应该是a < 11之类的东西吗? (打印语句取决于if- 显然你永远不会到达那里。) -
您在第一个
else块中是否缺少{ braces }?无论如何,b将重置为0。你为什么要遵循一个过时的教程,它有main()而不是int main(void)? -
为什么要使用如此神秘的变量名,以至于您需要注释来解释每个变量是什么?为什么不将变量命名为
array_position、word_length等?
标签: c output console-application histogram