I believe I've written the readability.c program correctly to count letters, words, and sentences based on readability prompt and calculate the grade index. But whenever I test the grade index, I'm getting certain grade levels incorrect.
For example:
Text input: In my younger and more vulnerable years my father gave me some advice that I've been turning over in my mind ever since.
The return is Grade 9 but it should be Grade 8.
Can anyone provide me with assistance on how to fix this?
Thank you! :)
#include <cs50.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <math.h>
int count_letters(string text);
int count_words(string text);
int count_sentences(string text);
int main(void)
{
//Get string of text from human
string text = get_string("Text: ");
//Implement function of count_letters
int countletters = count_letters(text);
//Implement function of count_words
int countwords = count_words(text);
//Implement function of count_sentences
int countsentences = count_sentences(text);
//Grade index formula (index = 0.0588 * L - 0.296 * S - 15.8)
//L is average number of letters in 100 words (countletters/countwords * 100)
//S is average number of sentences in 100 words (countsentences/countwords * 100)
float l = (((float) countletters / (float) countwords) * 100.0);
float s = (((float) countsentences / (float) countwords) * 100.0);
float index = ((0.0588 * l) - (0.296 * s) - 15.8);
float grade = floor(index);
//If grade index is lower than 1
if (index < 1)
{
printf("Before Grade 1\n");
}
//If grade index is higher than 16+
else if (index > 16)
{
printf("Grade 16+\n");
}
//If grade index is above 1 and below 16 print the grade index that's calculated
else
{
printf("Grade %.f\n", grade);
}
}
//count_letters function performance
int count_letters(string text)
{
//Declaring lettercount variable
int lettercount = 0;
//Looping over the letters in the text input by human
for (int i = 0, n = strlen(text); i < n; i++)
{
//If the character is a letter
if (isalpha(text[i]))
//Incrememnt lettercount
lettercount++;
}
return lettercount;
}
//count_words function performance - count number of words in a string
int count_words(string text)
{
//Declaring wordcount variable
int wordcount = 0;
//Looping over the number of spaces to determine number of words in the text input by human
for (int i = 0, n = strlen(text); i < n; i++)
{
if (i < n - 1 && isspace(text[i]))
{
wordcount++;
}
}
return wordcount;
}
int count_sentences(string text)
{
//Declaring sentencecount variable
int sentencecount = 0;
//Looping over the number of punctuation marks to determine number of stences input by human
for (int i = 0, n = strlen(text); i < n; i++)
{
if (text[i] == '.' || text[i] == '!' || text[i] == '?')
{
sentencecount++;
}
}
return sentencecount;
}
[1]: https://i.sstatic.net/y8e21.png