0

I am fairly new to coding and im trying to complete Readability in Problem Set 2. I have coded how to count the letters, words, and sentences but now I am trying to make it calculate the grade level correctly before printing out the correct grade. I can get it to compile but the problem is when I put in text (I used the copy/paste grade 5 text from the course material) it returns a "-nan" value. I think this means i need to round a decimal point somewhere but im not sure where. I have already tried printing the grade with a "%.1f" and I know I can use the round function but I think the problem is before then in my code i just don't know where. Thanks for any advice! Here is my code:

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


int main(void)

{
    string t; int letters = 0;

// Prompts User for text
    {
    t = get_string("Text: ");
    }

//counts letters


for (int i = 0;((t[i]) != '\0'); i++)
    {

        if (isalpha(t[i]))
        (letters++);

    }

// prints letters

{ printf("Letters: %i\n", letters);}

// count words by counting each space

int q = 0; int words = 0;
while ((t[q]) != '\0')
 {
     if ((t[q]) == ' ')(words++);
     q++;
 }

// Prints Amount of Words

{ printf("Words: %i\n", (words + 1));}

// counts sentences by incrementing int when recognizing .,?,!
{
    int x = 0; int sentences = 0;
    while ((t[x]) != '\0')
    {
        if ((t[x]) ==  '.' || (t[x]) == '?' || (t[x]) == '!')(sentences++);
        x++;
    }

// Prints amount of sentences

    { printf("Sentences: %i\n", sentences);}

// Calculate Grade Level

{   float p = words/100; 
    float L = letters / p;
    float S = sentences / p;
    float index = 0.0588 * L - .296 * S -15.8;

    printf( "Grade: %f\n", index);

}


}} 
0

words is an int, so "words/100" performs integer division regardless of the fact you are assigning the result to a float. If words is less than 100, that means when the decimal is discarded by the division operation, the result will be 0, and dividing by 0 (now the value of p) is not a number (nan).

If you change 100 to 100.0, the compiler will recognise it as a floating point value and perform division as such.

1
  • the answer was so simple lol. Thank You! Now I can continue my work. – Dre Johnson Nov 30 '20 at 1:59

You must log in to answer this question.

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