如何将字母频率更改为百分比?

时间:2014-10-27 08:23:06

标签: c percentage frequency letter

#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会给我一个-0.7500,b - 0.2500。

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

另外,如果我这样做,用户输入字符串直到EOF,我是否只删除“输入字符串”打印语句并将while(string [c]!='\ 0')更改为while(字符串[c]!= EOF)?

3 个答案:

答案 0 :(得分:0)

只需添加一个累积变量,每次读取一个字符时,它会加1(假设您要计算有效字符a-z和A-Z中的频率)。最后,将计数除以这个变量。

#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;
}

答案 1 :(得分:0)

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

100.0 * count[c] / strlen(string)

获得百分比

答案 2 :(得分: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);

    }
   }