我试图通过创建一个水平方向的直方图来测量用户输入中不同长度的单词的频率来解决 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--
等等。它还会忽略输入中一个或多个单词未表示的任何长度。但是,上面显示的代码根本不返回任何输出,而且我已经研究这个问题三天了。
我看不到什么阻止我的代码产生所需的输出?
最佳答案
在这个循环中
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);
您需要检查while (a < 11)
而不是while (a > 11)
并且(正如@WeatherVane 所指出的):
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;
看起来很可疑,你是不是忘记了第二个 block 周围的大括号?
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;
}
关于C 字数统计直方图应用程序不返回输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35325672/