如何用Pascal统计单词字母数?完善偶数字母数单词统计程序
修改后的Pascal程序(统计字母数为偶数的单词数量)
原程序存在无法处理连续空格、未在单词结束时判断字母数奇偶、遗漏最后一个单词统计的问题,以下是完善后的代码:
program test; var c : char; currentWordLength : integer; // 当前单词的字母数 evenWordCount : integer; // 字母数为偶数的单词数量 inWord : boolean; // 标记是否处于单词中,避免连续空格重复计数 begin currentWordLength := 0; evenWordCount := 0; inWord := false; writeln('请输入字符串'); read(c); while (c <> #13) and (c <> #10) do // 读取字符直到回车换行 begin if c <> ' ' then begin inc(currentWordLength); inWord := true; // 标记进入单词状态 end else begin if inWord then // 仅当之前处于单词中时,处理单词结束逻辑 begin if currentWordLength mod 2 = 0 then inc(evenWordCount); // 字母数为偶数则统计数+1 currentWordLength := 0; // 重置当前单词长度 inWord := false; // 标记退出单词状态 end; end; read(c); end; // 处理最后一个未以空格结尾的单词 if inWord then begin if currentWordLength mod 2 = 0 then inc(evenWordCount); end; writeln('字母数为偶数的单词数量: ', evenWordCount); end.
代码说明:
inWord变量避免连续空格被误判为多个单词,只有从非空格切换到空格时,才判定一个单词结束。- 每次单词结束时,立即检查字母数是否为偶数,符合条件则更新统计数。
- 循环结束后额外检查一次,确保最后一个无空格结尾的单词也被统计。
内容的提问来源于stack exchange,提问作者Илья
相关产品推荐
相关产品推荐

