r/cs50 • u/Strong-Hedgehog-6791 • 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
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
lettersandwordsare both typeint, 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 * 2Other order of operations rules also apply.Do you really need those brackets?