CodingDinosaur
CodingDinosaur

Reputation: 3

CS50x Pset 2 Readability: Why are L and S not correctly calculated?

I'm a beginner in programming and I'm working on this problem: https://cs50.harvard.edu/x/2020/psets/2/readability/

Here's my code:

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

int main(void)
{
    string text = get_string("Text: ");
    // L = (letters in total) / (words in total) * 100
    // S = (sentences in total) / (words in total) * 100

    int letters = 0; // amount of letters contained in the text.
    int sentences = 0; // amount of sentences in the text.
    int words = 0; // amount of words in the text.
    float L;
    float S;
    float grade;

    for (int i = 0, n = strlen(text); i < n; i++) // loop through each letter in this txt.
    {
        if ((text[i] >= 65 && text[i] <= 90) || (text[i] >= 97 && text[i] <= 122)) // check if the current byte is a letter.
        {
            letters++;
        }
        else if (text[i] == '.' || text[i] == '!' || text[i] == '?') // check if the current byte is the end mark of the sentence.
        {
            sentences++;
        }
        else if (text[i] == ' ') // check if the current byte is a space.
        {
            words++;
        }
    }

    L = (float) letters / (float) words * 100;
    S = (float) sentences / (float) words * 100;
    grade = 0.0588 * L - 0.296 * S - 15.8;

    printf("L = %f, S = %f\n", L, S);
    printf("letters: %i\n", letters);
    printf("words: %i\n", words + 1);
    printf("sentences: %i\n", sentences);
    printf("grade: %f\n", grade);
}

I think that my code is logically correct, and I can't tell any difference compared to others. However, there's trouble when I tried to get the value of L and S which are presented just like below:

L = (float) letters / (float) words * 100;
S = (float) sentences / (float) words * 100;

With the sample input sentence

Congratulations! Today is your day. You're off to Great Places! You're off and away!

the variable letters and words are supposed to be 65 and 14, therefore

L = (float) 65 / (float) 14 * 100;

The correct answer should be 464.2, but instead, I got 500.0.

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

int main(void)
{
    int a = 65;
    int b = 14;
    float c = (float) a / (float) b * 100;
    printf("%f\n", c);
    printf("%f\n", (float) a);
    printf("%f\n", (float) b);
    printf("%f\n", (float) a / (float) b);
}

Please help! I really don't know how to figure the issues out!

Upvotes: 0

Views: 153

Answers (1)

Barmar
Barmar

Reputation: 781974

You're not counting the last word in the last sentence, since there's no space after it.

Add

words++;

after the end of the loop to count the last word.

And since you're adding 1 there, you don't need to use words + 1 when printing the number of words.

Upvotes: 1

Related Questions