【问题标题】:Pascal how to count the number of letters in a word?Pascal 如何计算一个单词中的字母个数?
【发布时间】:2022-12-11 10:46:28
【问题描述】:

以前,该程序计算字符串中字母和单词的总数。现在我试图让它确定有多少个单词有偶数个字母。准确的说是一个字一个字的。告诉我如何完成。

program test;
var
  c : char;
  i : integer;
  numOfChar : integer;
  rem : integer;
begin
  i := 1;
  numOfChar := 0;
  rem := 0;
  c := ' ';
  writeln('Enter your string');
  read(c);
  
  while (c <> #13) and (c <> #10) do
  begin
    if c <> ' ' then inc(numOfChar)
    else inc(i);

    rem := numOfChar mod 2;
    read(c);     
  end;

  writeln('count of words: ', i);
  writeln('count of chars: ', numOfChar);
  writeln('rem: ', rem)
end.

这是我没有完成的代码。

【问题讨论】:

  • 使用“not odd()”来测试一个数是否为偶数。
  • 在我看来,您的代码中存在逻辑错误。输入五个空格和<enter>,会显示输入了五个字!单独一个空间是不可靠的。引入一个变量,比如inWord: boolean并将其初始化为false。当用户输入 char <> 空间时,将其设置为 true 并增加 char 计数器。当用户输入 char = space 和 inWord = true 时,将其设置为 false 并递增 words。此时您还可以检查字符计数器是否为偶数。

标签: char pascal


【解决方案1】:

如果你想计算单词数,你需要知道什么时候空格是有意义的,什么时候它们是不是.例如考虑一个字符串' hello world '。

如果您使用名为 in_word 的布尔值设置为 false 进入字符串循环。只有当我们检测到非空格字符时,我们才会将其设置为 true。我们还有整数值 word_count 和 word_length。两者都设置为0。当in_word 为真并且我们检测到空格时,我们将递增word_count。

Char:        ' '
in_word:     false
word_count:  0
word_length: 0

Char:        ' '
in_word:     false
word_count:  0
word_length: 0

Char:        'h'
in_word:     false -> true
word_count:  0
word_length: 1

Char:        'e'
in_word:     true
word_count:  0
word_length: 2

Char:        'l'
in_word:     true
word_count:  0
word_length: 3

Char:        'l'
in_word:     true
word_count:  0
word_length: 4

Char:        'o'
in_word:     true
word_count:  0
word_length: 5

Char:        ' '
in_word:     false
word_count:  1
word_length: 0

Char:        'w'
in_word:     false -> true
word_count:  1
word_length: 1

Char:        'o'
in_word:     true
word_count:  1
word_length: 2

Char:        'r'
in_word:     true
word_count:  1
word_length: 3

Char:        'l'
in_word:     true
word_count:  1
word_length: 4

Char:        'd'
in_word:     true
word_count:  1
word_length: 5

Char:        ' '
in_word:     false
word_count:  2
word_length: 0
begin
  in_word := false;
  word_count := 0;
  word_length := 0;

  for i := 1 to length (input) do
  begin
    if in_word && input[i] = ' ' then
      begin ... end
    else if in_word then
      begin ... end
    else if input[i] = ' ' then
      begin ... end
    else
      begin ... end
  end

现在,您能否修改这组步骤,使其在遇到五个字母的单词时递增 five_letter_words 变量?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-06-21
    • 2015-11-18
    • 2022-11-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-08
    相关资源
    最近更新 更多