I'm having problems with the Pset 2 problem: readability.

The goal of exercise is to implement a program that computes the approximate grade level needed to comprehend some text using the Coleman-Liau index.

When running my code, I get the wrong grade for all of the tests and I have no clue why. I believe it has perhaps something to do with count_words (however I don't know how to fix my code)

enter image description here

The correct grade of example above should be Grade 5 instead of 2.

Note: compiling works and gives no errors.

Hopefully someone can help me with this. Thank you in advance.

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

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

    int count_letters = 0, count_words = 0, count_sentences = 0;

//Count letters, words, sentences
    for (int i = 0, i < strlen(text); i++)
        if (isalpha(text[i])) {

        if (isspace(text[i]) || text[i] == '\0') {

        if (text[i] == '.' || text[i] == '!' || text[i] == '?') {

    printf("%d letter(s)\n", count_letters);
    printf("%d word(s)\n", count_words);
    printf("%d sentence(s)\n", count_sentences);

//The Coleman-Liau index
    float L = count_letters / count_words * 100;
    float S = count_sentences / count_words * 100;
    float index = ((0.0588 * L) - (0.296 * S) - 15.8);

        if (round(index) < 1)
            printf("Before Grade 1\n");

        else if (round(index) >= 16)
            printf("Grade 16+\n");

            printf("Grade %f\n", round(index));

There are several problems. First, the word count is off by 1. Hint: is the code actually reading the end of string marker?

Second, and most important, look at the calculations:

float L = count_letters / count_words * 100;
float S = count_sentences / count_words * 100;

Each of the elements in the calculations is an integer. That means that this is integer division, not regular division. Only the overall result is cast as a float, after the damage has been done.

Finally, the end result should be an integer, not a float.

If this answers your question, please click on the check mark to accept. Let's keep up on forum maintenance. ;-)

You must log in to answer this question.

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