如何将字母频率更改为百分比?
#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)?
只要添加一个累加变量,每次读取一个字符时,它都会增加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;
}
是的!忘记修改那一个:(!! – vicsana1 2014-10-27 08:33:30
这将不能正确计算var:accum。因为字符串可能包含除az和AZ以外的可打印字符,例如',','。','?'等等 – user3629249 2014-10-28 03:32:16
,使用
100.0 * count[c]/strlen(string)
得到的百分比
在for循环中,COUT /串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);
}
}
感谢u @ user3121023 – 2014-10-27 08:40:15
通过将个人计数除以所有计数的总和?还是由字符串长度?不过,一定要使用浮点运算。 – 2014-10-27 08:27:00
'count [c] * 100.0/strlen(string)' – 2014-10-27 08:28:55
@Meehm我的意思是像MarkStechell提出的那样作为他的回答。更正了我之前的评论 – ha9u63ar 2014-10-27 08:33:04