【问题标题】:Printing letter frequency of a string打印字符串的字母频率
【发布时间】:2017-08-30 10:27:10
【问题描述】:

只是想知道为什么这不起作用。我想使用 getchar() 读取输入并打印字符、百分比/100 和频率。例如你好将打印: 'a' 0.200000 1 以此类推每个字符到 z。 它接受输入但不打印任何内容:

#include <stdio.h>
int main (void) {
    double array[26] = {0};
    int i=0;
    double count=0;
    int j =0;
    int start = 'a';
    int point = 0;
    while (i != EOF) {
            i=getchar();
            if(i>='a' && i<='z' && i!=-1) {
                point= i-'a';
                array[point] = array[point] +1;
                count= count+1;
            }
            else if(i>='A' && i<='Z' && i!=-1) {
                point = i - 'A';
                array[point] = array[point] +1;
                count= count+1;
            }
    }
    while (j<=25) {
        printf("'%c' %.6f %.0f", start, (count/array[j]), array[j]);
        j++;
        start++;
    }
}

【问题讨论】:

  • 注意:i!=-1if(i&gt;='A' &amp;&amp; i&lt;='Z' &amp;&amp; i!=-1) 中不需要。 A-Z 不能有负值。

标签: c string frequency getchar letter


【解决方案1】:

你计算百分比的方式是错误的。

printf("'%c' %.6f %.0f", start, (count/array[j]), array[j]);

应该是

printf("'%c' %.6f%% %.0f\n", start, (array[j]/count*100), array[j]);

【讨论】:

  • 是的,这是一个很好的解决方案,但是,它不打印任何内容,并在 i=getchar() 处停止。出于某种原因,当它停止时,我总是等于 10。
  • 什么等于 10? @maxphat
  • 执行在第 10 行 i=10 时停止,其中 i=getchar()
  • @maxphat 如果从终端输入数据,在 Windows 上要停止输入时按​​enter 并输入ctrl + z,或在要停止时按enter 并输入ctrl + d在 Linux 上输入。
  • 当我点击 crtl + c 时,它显示。我输入后是否需要点击ctrl + d?
猜你喜欢
  • 2014-06-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-25
  • 1970-01-01
  • 2019-07-16
  • 2018-09-08
  • 2021-12-31
相关资源
最近更新 更多