0

when you input -

Alice was beginning to get very tired of sitting by her sister on the bank, and of having nothing to do: once or twice she had peeped into the book her sister was reading, but it had no pictures or conversations in it, "and what is the use of a book," thought Alice "without pictures or conversation?"

it should output grade 8 but it outputs grade 9

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

int main(void)
{
    float l = 0;
    float w = 1;
    float s = 0;

// get text from user
string text= get_string("Your text:");

//string longiness
     int length = strlen(text);


    for (int k = 0; k < length; k++)
{
// num of all letters
        if isalpha(text[k])
        {
             l++;
        }

// num of words
            if isalpha(text[k])
            {
       if (isspace(text[k-1]) || text[k-1] == '!' || text[k-1] == '.' || text[k-1] == '?')
    {
       w++;
    }
            }   

// num of sentences
    if (text[k] == '!' || text[k] == '.' || text[k] == '?')
    {
       s++;
    }
    
}


// calculating avarge of letters per 100 words
float L = l / w * 100;
// calculating average number of sentences per 100 words
float S = s / w * 100;

// Coleman-Liau index calculating
int index = round((0.0588 * L) - (0.296 * S) - 15.8);

// output: what grade is text for
if (index < 1)
printf("Before Grade 1\n");

  else if (index <= 16 && index > 1)
        printf("Grade %i\n", index);
        
    else
printf("Grade 16+\n");

}
Weather Vane
  • 33,872
  • 7
  • 36
  • 56
Mertin27
  • 1
  • 1

1 Answers1

1

I fixed the indentation of your code

// num of words
if (isalpha(text[k]))             // I added missing parenthesis
{
    if (isspace(text[k-1]) || text[k-1] == '!' || text[k-1] == '.' || text[k-1] == '?')
    {
        w++;
    }
}

Your code does not count the without word in thought Alice "without pictures because it starts with a quote.

And, as stated in comments, you need to prevent access to text[-1] which causes Undefined Behaviour.

pmg
  • 106,608
  • 13
  • 126
  • 198