【发布时间】:2023-03-22 09:52:01
【问题描述】:
嗨,所以我想弄清楚为什么在我运行我的代码时总是出现 e 的百分比。正如您在程序中看到的那样,我需要找到字符串中的字符数和单词数,以及 e 在所述字符串中的频率,最后我需要找到字符 e 在所述字符串中的百分比。教授说要使用gets(),但没有其他预制函数。我当然不是直接要求答案,但如果你能指出我正确的方向或我哪里出错了,我将不胜感激(这里显然是初学者)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char str[100];
int i, c_number, space, c_e, percentage;
c_number = 0;
space = 0;
c_e = 0;
percentage = 0;
printf("Enter a string: ");
gets(str);
for(i=0; str[i]!='\0';i++)
{
c_number++;
if(str[i]==' ')
{
space++;
}
if(str[i]=='e')
{
c_e++;
percentage = (c_e/c_number)*100;
}
}
printf("\n the number of characters is: %d and the number of words is: %d", c_number, space+1);
printf("\n the number of e in the string is: %d", c_e);
printf("\n the percentage of e in the string is: %d ", percentage);
return 0;
}
【问题讨论】:
-
你有什么问题?
-
请注意,
percentage = (c_e/c_number)*100;是整数除法,可能不会产生所需的值。 -
整数除法会截断任何小数部分,例如
7/4 = 1因为答案确实是 1.75,但小数部分 0.75 被删除了。在您的代码中,c_e几乎总是小于c_number,因此除法返回 0,乘以 100 仍为 0。解决方案是先乘以 100,例如(c_e * 100) / c_number -
您还需要计算
percentage在循环完成后,当您获得最终计数时。当找到e时,代码当前会更新percentage。所以c_number中的值通常会太低(这是找到最后一个e时的计数,而不是总计数)。 -
告诉你的教授你不会使用
gets。没有人应该。
标签: c string word-frequency