[英]My attempt at K&R Exercise 1-13 is making bars way too long
我的代碼是
#include <stdio.h>
#include <ctype.h>
main() {
int nwords[10];
int c;
int i;
int firstLetter;
c=0;
i=0;
firstLetter=0;
while ((c = getchar()) != EOF) {
if (isalpha(c)) {
firstLetter = 1;
i++;
}
if (firstLetter != 0) {
nwords[i]++;
i=0;
}
}
for (i=0; i<10; i++) {
printf("%d, ");
while (nwords[i] > 0) {
printf("=");
-- nwords[i];
}
if (nwords[i] == 0) {
printf("/n");
}
}
}
我希望輸出是一個水平直方圖,它可以顯示輸入文件中單詞長度的頻率,如下所示:
10 ===
9 ==
8
7 ====
6 =
5 ======
4 ===
3 =
2 =
1 =
但是,相反,我的程序將垃圾郵件發送給空格鍵,直到必須將其殺死為止。
我做錯了什么? 謝謝。
在for (i=0; i<10; i++)
將printf("%d, ")
for (i=0; i<10; i++)
更改為printf("%d", variable)
給出要用%d
替換其值的變量。
並替換printf("/n");
使用printf("\\n");
除了surjit的答案外,您還需要進行以下更改:
int nwords [10] = {0};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.