求找错
本帖最后由 代码农民 于 2016-11-3 23:26 编辑《C程序设计语言—第2版》练习1 -13
编写一个程序,印输入中单词长度的直方图。(我看的是水平的直方图程序的答案,但是运行结果...)
上代码:
/* 水平方向直方图 */
#include<stdio.h>
#define MAXHIST 15 /*max length of histogram */
#define MAXWORD 11/*max length of a word */
#define IN 1 /* inside a word */
#define OUT 0 /* outside a word*/
main()
{
int c,i,nc,state;
int len;
int maxvalue;
int ovflow;
int wl;
state = OUT;
nc = 0;
ovflow = 0;
for (i = 0; i < MAXWORD; ++i)
wl = 0;
while ((c = getchar()) != EOF) {
if (c == ' ' || c == '\n' || c == '\t') {
state = OUT;
if (nc > 0)
if (nc < MAXWORD)
++wl;
else
++ovflow;
nc = 0;
} else if (state == OUT) {
state = IN;
nc = 1;
} else
++nc;
}
maxvalue = 0;
for (i = 1; i < MAXWORD; ++i)
if (wl > maxvalue)
maxvalue = wl;
for (i = 1; i < MAXWORD; ++i) {
printf("%5d - %5d : ",i,wl);
if (wl > 0) {
if ((len = wl * 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);
}
输入下面的文字:
Tacloban city administrator Tecson Lim said that the death toll in the city alon
e "could go up to 10,000." Tacloban is the Leyte provincial capital of 200,000 p
eople and the biggest city on Leyte Island.
^Z
我的结果是:
我在百度搜索的结果是:
答案是原书答案。请问代码哪里有问题?
/* 水平方向直方图 */
#include<stdio.h>
#define MAXHIST 15 /*max length of histogram */
#define MAXWORD 11/*max length of a word */
#define IN 1 /* inside a word */
#define OUT 0 /* outside a word*/
main()
{
int c,i,nc,state;
int len;
int maxvalue;
int ovflow;
int wl;
state = OUT;
nc = 0;
ovflow = 0;
for (i = 0; i < MAXWORD; ++i)
wl = 0;
while ((c = getchar()) != EOF) {
if (c == ' ' || c == '\n' || c == '\t') {
state = OUT;
if (nc > 0)
{
if (nc < MAXWORD)
++wl;
else
++ovflow;
}
nc = 0;
} else if (state == OUT) {
state = IN;
nc = 1;
} else
++nc;
}
maxvalue = 0;
for (i = 1; i < MAXWORD; ++i)
if (wl > maxvalue)
maxvalue = wl;
for (i = 1; i < MAXWORD; ++i) {
printf("%5d - %5d : ",i,wl);
if (wl > 0) {
if ((len = wl * 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);
} if ((len = wl * MAXHIST / maxvalue) <= 0);
这句 多了一个分号
代码好乱 整理过后基本就正常了 - - fc1735 发表于 2016-11-4 01:28
/* 水平方向直方图 */
#include
谢谢啊!!!!!! ^_^^_^^_^^_^ 发表于 2016-11-4 01:49
if ((len = wl * MAXHIST / maxvalue)
谢谢!!!! 再次谢谢楼上两位!!!!
页:
[1]