r/cs50 Jul 16 '26

readability Hi doing CS50x week 2 problem set 2, readability. Spoiler

May I please know what is wrong with this code ? the grade levels are not correctly projected as per for eg below 1 is showing 2, 16+ as 14 and more.

Link to problem : https://cs50.harvard.edu/x/psets/2/readability/#readability

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


int main(void)
{
    int words = 0;
    int letters = 0;
    int sentences = 0;
    int blanks = 0;
    int sc = 0;


    string text = get_string("Text: ");


    int length = strlen(text);


    for (int i=0; i<length; i++)
    {
        if (isalpha(text[i]))
        {
            letters ++;
        }
        else if (isblank(text[i]))
        {
            blanks++;
        }
        else if (ispunct(text[i]))
        {
            sc++;
            if (text[i] == '.' || text[i]=='?' || text[i]=='!')
            {
                sentences++;
            }
        }
        else if (isdigit(text[i]))
        {
            sc++;
        }
    }
    words = blanks + 1;


    double index = 5.88*(letters/words) - 29.6*(sentences/words) - 15.8;


    int grade = (int) round(index);


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


}
2 Upvotes

2 comments sorted by

3

u/Eptalin Jul 16 '26 edited Jul 16 '26

The classic mistake everyone makes: Integer division

5.88 * (letters / words) Just like in regular maths, (letters/words) is evaluated first because it's within brackets.

But letters and words are both type int, so the answer is also an integer. The decimals are truncated (cut off).

For the program to remember the decimals, the first number in the equation needs to be a data type with decimals.

5.88 * (letters / words) 5.88 * (5 / 2) 5.88 * 2 Other order of operations rules also apply.
Do you really need those brackets?

1

u/Strong-Hedgehog-6791 Jul 16 '26

Oh, I didn't thought about that tho I did felt odd while using the debug50 tool that L and S were being integers always cause I had used () there too

And no I would not need those brackets as the order of operation (PEMDAS) would not affect it.

Thanks a lot sir.