0
#include <stdio.h>
#include <string.h>

int main()
{
   char string[100];
   int c = 0, count[26] = {0};

   printf("Enter a string\n");
   gets(string);

   while ( string[c] != '\0' )
   {

      if ( string[c] >= 'a' && string[c] <= 'z' ) 
         count[string[c]-'a']++;

      else if (string[c] >= 'A' && string[c] <= 'Z')
         count[string[c]-'A']++;
      c++;

   }

   for ( c = 0 ; c < 26 ; c++ )
   {
      if( count[c] != 0 )
     printf( "%c %d\n", c+'a', count[c]);
   }

   return 0;
}

所以我设法让代码将字母频率计算为一个数字。但是我的作业告诉我将其表示为整个字符串的百分比。

例如,输入 aaab 会给我 a - 0.7500,b - 0.2500。

我将如何修改此代码以将其表示为百分比而不是数字?

另外,如果我要在用户输入字符串直到 EOF 的情况下执行此操作,我是否只需删除“输入字符串”打印语句并将 while (string[c] != '\0') 更改为 while (string[c] != EOF)?

4

3 回答 3

0

只需添加一个累积变量,每次读取一个字符时,它都会加一(假设您要计算有效字符 az 和 AZ 之间的频率)。最后,将计数除以此类变量。

#include <stdio.h>
#include <string.h>

int main()
{
   char string[100];
   int c = 0, count[26] = {0};
   int accum = 0;

   printf("Enter a string\n");
   gets(string);

   while ( string[c] != '\0' )
   {

      if ( string[c] >= 'a' && string[c] <= 'z' ){
         count[string[c]-'a']++;
         accum++;
      }

      else if (string[c] >= 'A' && string[c] <= 'Z'){
          count[string[c]-'A']++;
          accum++;
      }
      c++;
   }

   for ( c = 0 ; c < 26 ; c++ )
   {
      if( count[c] != 0 )
          printf( "%c %f\n", c+'a', ((double)count[c])/accum);
   }

   return 0;
}
于 2014-10-27T08:30:37.657 回答
0

在你的第二个 for 循环中,使用

100.0 * count[c] / strlen(string)

得到百分比

于 2014-10-27T08:30:40.627 回答
0

在 for 循环中,cout/string len 逻辑将给出比率值。

   for ( c = 0 ; c < 26 ; c++ )
   {
      if( count[c] != 0 ){
    float val = count[c] ;
    val = (val/strlen (string)) * 100.0;

             printf( "%c %d %%:%f\n", c+'a', count[c], val);

    }
   }
于 2014-10-27T08:35:32.430 回答