Hi Folks, I hope everyone is fine. I just finished coding my PSET2 on readability but my code is not working for some grade tests:
:) readability.c exists
:) readability.c compiles
:( handles single sentence with multiple words
expected "Grade 7\n", not "Grade 9\n"
:( handles punctuation within a single sentence
expected "Grade 9\n", not "Grade 11\n"
:( handles more complex single sentence
expected "Grade 8\n", not "Grade 9\n"
:) handles multiple sentences
:) handles multiple more complex sentences
:) handles longer passages
:( handles questions in passage
expected "Grade 2\n", not "Grade 3\n"
:) handles reading level before Grade 1
:) handles reading level at Grade 16+
Here is the finished code:
#include <stdio.h>
#include <cs50.h>
#include <math.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
//This code snippet computes the approximate grade level needed to comprehend some text
//We will implement this program using the Coleman-Liau index.
//The Coleman-Liau index of a text is designed to output what grade level is needed to understand the text.
//The formula is: index = 0.0588 * L - 0.296 * S - 15.8
//L is the average number of letters per 100 words in the text, and S is the average number of sentences per 100 words in the text.
int main(void)
{
int word = 0;
int k;
//Prompting the user for some text
string s = get_string("Text: ");
//Counting the number of words in the string
for (k = 0; s[k] != '\0'; k++)
{
if (s[k] == ' ' || s[k] == '\n' || s[k] == '\t')
{
word++;
}
}//End for
//Counting the number of sentences
int ch, sentence = 0;
ch = strlen(s);
for (int i = 0; i<ch; i++)
{
if (s[i] == '.' || s[i] == '?' || s[i] == '!')
{
sentence++;
}
}//End for
//Here we are reading the string one character at a time:
//If the character at ith position is not a letter, we move the next character to occupy the position
int j;
for (int i = 0; s[i] != '\0'; i++)
{
while (!((s[i] >= 'a' && s[i] <= 'z') || (s[i] >= 'A' && s[i] <= 'Z') || s[i] == '\0'))
{
for (j = i; s[j] != '\0'; j++)
{
s[j] = s[j + 1];
}//End For Loop
s[j] = '\0';
}//End While Loop
}//End for Loop
//Counting the letters of the resultant string
int newtotal = 0;
for (int i = 0; s[i] != '\0'; i++)
{
newtotal++;
}
//Now calculating the Coleman-Liau index in order to know the reading grade level
//The formula of the index is: index = 0.0588 * L - 0.296 * S - 15.8
int index = 0;
int L = 0, S = 0;
index = 0.0588 * L - 0.296 * S - 15.8;
//printf("%i letter(s)\n", newtotal);
//printf("%i word(s)\n", word);
//printf("%i sentence(s)\n", sentence);
index = round(0.0588 * (100 * newtotal / word) - 0.296 * (100 * sentence / word) - 15.8);
if (index <= 1)
{
printf("Before Grade 1\n");
}
else if (index <= 16)
{
printf("Grade %i\n", index);
}
else
{
printf("Grade 16+\n");
}
}//End main function