pascal问题,求用string做:求输入一句英文句子,求所有单词的平均长度.

问题描述:

pascal问题,求用string做:求输入一句英文句子,求所有单词的平均长度.
要用最最最简洁、简单的做出来,谢谢!
1个回答 分类:综合 2014-09-17

问题解答:

我来补答
① 平均长度,用了浮点,如果有需要,可以改成整数② 统计是以a~z,A~Z,以及' - 为单词进行的,如果有需要,也可以改成只按字母统计.program words_average_length;
var
    instr : String;
    word_cnt, word_lengths, i : Integer;
    isWordCount : Boolean;
begin
    readln(instr);
    word_cnt := 0; word_lengths := 0; isWordCount := false;
    for i := 1 to length(instr) do 
    begin
        if instr[i] in ['A'..'Z','a'..'z','''','-'] then 
            begin
                inc(word_lengths); 
                if not isWordCount then begin isWordCount := true; inc(word_cnt); end
            end
        else
            begin if isWordCount then isWordCount := false; end; 
    end;

    writeln('word count = ', word_cnt);
    writeln('word length sum = ', word_lengths);
    writeln('word length average = ', word_lengths / word_cnt:10:2);
end.③ 运行:this's A Test!
word count = 3
word length sum = 11
word length average =       3.67
再问: 就是可以用最简单的只用string里面的函数,不要用in,not什么的,还不会用那种,就只需要用string就好了,并且不要用boolean好吗?
再答: program words_average_length;
var
    instr : String;
    word_cnt, word_lengths, i, isWordCount : Integer;     
begin
    readln(instr);
    word_cnt := 0; word_lengths := 0; isWordCount := 0;
    for i := 1 to length(instr) do 
    begin
        if ( (instr[i] >= 'A') and (instr[i] <= 'Z') or 
            (instr[i] >= 'a') and (instr[i] <= 'z')  or 
            (instr[i] = '''') or (instr[i] = '-') ) then 
            begin
                inc(word_lengths); 
                if isWordCount = 0 then begin isWordCount := 1; inc(word_cnt); end
            end
        else
            begin if isWordCount = 1 then isWordCount := 0; end; 
    end;

    writeln('word count = ', word_cnt);
    writeln('word length sum = ', word_lengths);
    writeln('word length average = ', word_lengths / word_cnt:10:2);
end.
 
 
展开全文阅读
剩余:2000