【问题标题】:Calculate the percentage of the character e in a string计算字符串中字符e的百分比
【发布时间】: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


【解决方案1】:
#include <stdio.h>
#include <ctype.h>

int main(void) {
    const char * input = "This is a long random string that might contain a few letters.";
    
    int freq[26] = {0};
    
    
    for(char* c=input; *c; isalpha(*c) ? freq[tolower(*c++)-'a']++:c++); 

    printf("the number of characters is: %d\n", strlen(input));
    printf("the number of e in the string is: %d\n", freq['e'-'a']);
    printf("the percentage of e in the string is: %d%%\n", 100*freq['e'-'a']/strlen(input));

    return 0;
}

【讨论】:

  • "%d"strlen(input) 冒着 OP 未定义行为的风险,
  • 嘿,我不允许使用 strlen 或指针,但感谢您的代码,我实际上能够弄清楚,所以谢谢:)(编辑:在单词指针中添加了“s”)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-08
  • 1970-01-01
  • 2019-09-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多