提问人:Jacky L. 提问时间:11/12/2023 最后编辑:Jacky L. 更新时间:11/12/2023 访问量:38
字数统计直方图
Word count histogram
问:
我想做一个程序,读取 .txt 文件中的段落,函数需要计算每个单词的长度,并将相同长度的单词数加到相应的频率中。例如,如果段落有 2 个长度为 5 的单词,则 bin = 2 的 bin 频率将为 5。
但是,我所有的 bin 和 freq 值在我的输出中都读取为 0,如下所示:
0.0/0.0 *
0.0/0.0 *
0.0/0.0 *
预期输出:
1.0/5.0 *****
2.0/4.0 ****
3.0/10.0 **********
哪个部分可能是问题所在?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void readTextFile(const char *filename, int bin[], int freq[], int *N);
void printHist(const float bin[], const float freq[], int N);
void plotHorizontalHist(const float bin[], const float freq[], int N);
void plotVerticalHist(const float bin[], const float freq[], int N);
void printHist(const float bin[], const float freq[], int N) {
for (int i = 0; i < N; i++) { //Verify the data
printf("%.1f %.1f\n", bin[i], freq[i]);
}
printf("\n");
}
void plotHorizontalHist(const float bin[], const float freq[], int N) {
for (int i = 0; i < N; i++) {
printf("%.1f/%.2f: ", bin[i],freq[i]);
// Print '*' for each unit of frequency
for (int j = 0; j < freq[i]; j++) {
printf("*");
}
printf("\n");
}
printf("\n");
}
void plotVerticalHist(const float bin[], const float freq[], int N) {
// Find the maximum frequency to scale the vertical bars
float maxFreq = 0;
for (int i = 0; i < N; i++) {
if (freq[i] > maxFreq) {
maxFreq = freq[i];
}
}
// Print the vertical histogram
for (int row = maxFreq; row > 0; row--) {
for (int i = 0; i < N; i++) {
if (freq[i] >= row) {
printf("* ");
} else {
printf(" ");
}
}
printf("\n");
}
// Print bin labels at the bottom
printf("%.0f", bin[0]);
for (int i = 1; i < N; i++) {
printf("%2.0f",bin[i]);
}
printf("\n");
}
void readTextFile(const char *filename, int bin[], int freq[], int *N) {
FILE *f;
char word[100];
if ((f = fopen(filename, "r")) != NULL) {
while (fscanf(f, "%s", word) == 1 && *N < 100) {
int len = strlen(word);
// Search for the length in the existing bins
int found = 0;
for (int i = 0; i < *N; i++) {
if (bin[i] == len) {
freq[i]++;
found = 1;
break;
}
}
// If the length is not found, create a new bin
if (!found) {
bin[*N] = len;
freq[*N] = 1;
(*N)++;
}
}
fclose(f);
} else {
printf("The file doesn't exist\n");
}
}
int main(int argc, char **argv) {
float bin[100];
float freq[100];
int N = 0;
if (argc > 1) {
readTextFile(filename,bin,freq,&N);
printHist(bin,freq,N);
plotHorizontalHist(bin,freq,N);
plotVerticalHist(bin,freq,N);
}
return 0;
}
答:
1赞
pmg
11/12/2023
#1
您的函数被定义为接受数组,但它们被定义为数组int
float
void readTextFile(const char *filename, int bin[], int freq[], int *N);
float bin[100];
float freq[100];
打开编译器警告并注意警告!
评论
0赞
Jacky L.
11/12/2023
谢谢,那是我的错。我在想我可以只使用 int,因为所有值都是整数,因为程序的另一部分在浮点上工作。
评论
printf("The file doesn't exist\n");
perror(filename)
;