简体   繁体   中英

Calculate the percentage of the character e in a string

hi so I'm trying to figure out why the percentage of e always comes up when I run my code. As you can see for the programme I need to find the number of characters and words in a string which is all good as well as the frequency of e in said string, lastly I need to find the percentage of the character e within said string. Prof said to use gets() but no other pre made functions. I of course am not asking for the answer directly but if you could point me in the right direction or where I'm going wrong it would be much appreciated (complete beginner here obviously)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM