0

I get the correct grade level output sometimes when running this code, but usually the grade level is off by one. This question has been asked before:

  1. CS50 Inconsistency of Results
  2. Inaccuracy in Readability Test Case
  3. Pset2 Readability: Grade calculation wrong
  4. Readability Wrong Grade

I couldn't decipher an answer from the above, one had to do with float division, another with word count, another with an inaccurate formula.

I submitted the program to submit50 already and just took the incorrect answers in stride, but if anybody can spot the error would very much like to understand what I'm missing.

Code here:

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


int main(void)
{

// Declare variables
int letters = 0;
int words = 0;
int sentences = 0;


// Get a string of text from the user
string text = get_string("Text: ");


// Find total number of letters/words/sentences
for (int i = 0; i <= strlen(text); i++)
{
    // Find letters using ASCII values
    if ( (text[i] >= 65 && text[i] <= 90) || (text[i] >= 97 && text[i] <= 122) )
    {
        letters += 1;
    }
    // Find words separated by a space (ASCII 32)
    else if (text[i] == 32)
    {
        words += 1;
    }

    // Find Periods (ASCII 46), Exclamations (ASCII 33), Question Marks (ASCII 63)
    else if (text[i] == 46 || text[i] == 33 || text[i] == 63)
    {
        sentences += 1;
    }
}


// Find average letters per 100 words
float L = (float) 100 * letters / words;


// Find average sentences per 100 words
float S = (float) 100 * sentences / words;


// Coleman Liau Index
float index = 0.0588 * L - 0.296 * S - 15.8;

// Grade Level
int grade = round(index);

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


}
1

The way your are adding up the words by detecting the espace caracter (ascii-32) is good except for one situation at the end of each text. The last word is not taken into account.

You must log in to answer this question.

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