看看这段程序问题出在哪里?当输入Hello, world! This is a C program!时,前2个单词的长度没有显示出来?问
看看这段程序问题出在哪里?
当输入Hello, world! This is a C program!时,前2个单词的长度没有显示出来?问题在哪呢?
代码如下:
- C/C++ code
#include "stdio.h"#include "stdlib.h"#define LENGTH (1000)#define OUT (0)#define IN (1)/*编写一个程序,打印输出中单词长度的水平直方图。*/main(){ int ch; int i,j; int nw=0; /*单词计数*/ int nc=0; /*单词长度计数*/ p=i[解决办法]
- C/C++ code
#define OUT (0)#define IN (1)/*编写一个程序,打印输出中单词长度的水平直方图。*/int main(){ int ch; int i,j; int nw=-1; /*单词计数*/ //int nc=0; /*单词长度计数*/ int state=OUT; /*字符是否在单词内*/ int wl[LENGTH]; /*声明一个数组,用于存放每个单词的长度*/ printf("Please enter some sentences:\n"); for(i=0;i<LENGTH;i++) wl[i]=0; /*初始化数组各成员的值为0*/ for(i=0;i<LENGTH&&((ch=getchar())!=EOF)&&(ch!='\n');i++) { if(ch>='a'&&ch<='z'||ch>='A'&&ch<='Z') { if(state==OUT) /*字符为单词的首个字母*/ { nw++; wl[nw]++; } else wl[nw]++; state=IN; } else { state =OUT; } } printf("\nOutput the histogram:\n"); for(i=0;i<=nw;i++) { printf("Word ID: %d:\t",i); for(j=0;j<wl[i];j++) /*单词长度以星号输出*/ putchar('*'); putchar('\n'); } putchar('\n'); system("pause"); return 0;}
[解决办法]
问题出在这个地方,因为你的“,”和“!”不是字母,而他们后面又都有一个空格,
所以当程序执行到“,”时就已经将行信息正确赋给wl[nw],此时nc=0;但是紧接着是一个空格,
又不是字母,些时nw没有变,所以刚被赋给的值又被清空了。
- C/C++ code
if(ch>='a'&&ch<='z'||ch>='A'&&ch<='Z') { if(state==OUT) /*字符为单词的首个字母*/ { nw++; nc++; state=IN; } else nc++; } else { wl[nw]=nc; nc=0; state =OUT; } 