0

Hi I am stuck on readability and am not sure what i am doing wrong

$ ./readability 
Text: one fish. two fish. red fish. blue fish
8
3
42
13
Grade 13

and my code:

#include <stdio.h>
#include <math.h>
#include <cs50.h>
#include <string.h>
#include <ctype.h>

int main() {
    string text = get_string("Text: ");

    int sentences = 0;
    int numberOfCharacters = strlen(text);
    int words = 0;

    bool foundLetter = false;

    for (int i = 0; i < numberOfCharacters; i++) {
        if (text[i] == ' ') {
            foundLetter = false;
        } else if (foundLetter == false) {
            words++;
            foundLetter = true;
        }
    }

    printf("%d\n", words);

    for (int x=0; x < numberOfCharacters; x++) {
        if (text[x] == '!' || text[x] == '.' || text[x] == '?') {
            sentences += 1;
        }
    }

    printf("%d\n", sentences);

    for (int a=0; a < numberOfCharacters; a++) {
        if (text[a]=='.') {
            numberOfCharacters++;
        }
    }

    printf("%d\n", numberOfCharacters);

    float averageWords = sentences / words * 100;
    float averageLetters = numberOfCharacters / words * 100;

    float nonRoundedIndex =  0.0588 * averageLetters - 0.296 * averageWords - 15.8;

    int index = round(nonRoundedIndex) - 1;

    printf("%d\n", index);

    if (index >= 16) {
        printf("Grade 16+\n");
    } else if (index <= 1) {
        printf("Before Grade 1 \n");
    } else {
        printf("Grade %d \n", index);
    }
}

2 Answers 2

0

You have a logic error in your code. You have a variable called numberOfCharacters that is set equal to strlen(text). This will make it the length of the text, including punctuation and spaces. Then, you are increasing this number for each time you encounter a period. This means that your loop for (int a = 0; a < numberOfCharacters; a++) will technically go out of the bounds of your text and start reading data positioned next to it in memory, which could lead to some unexpected results.

Look at this variable and figure out what it should be counting and what you want it is currently counting. Are they the same thing? Also, periods are not the only things that the problem's specification says can end sentences, so you might want to look at how you are calculating your number of sentences, too.

Hope this helps. If it does, feel free to click the check mark next to the answer. But if not, let me know and I will try to help further.

-1

I think the error in your code should be in how you are calculating the average of letters and sentences per word: float averageWords = sentences / words * 100 and float averageLetters = numberOfCharacters / words * 100;. You should actually multiply letters and sentences by 100 in each formula and then divide by words.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .