#include <stdio.h>
#include <cs50.h>
#include <string.h>
#include <math.h>
int letters = 0;
int words = 0;
int sentences = 0;
int main(void)
{
string text = get_string("Text: ");
printf("\n");
for(int j = 0; j < strlen(text); j++)
{
if((text[j] >= 'a' && text[j] <= 'z') || (text[j] >= 'A' && text[j] <= 'Z'))
{
letters++;
}
if(text[j] == ' ')
{
words++;
}
if(text[j] == '.' || text[j] == '?' || text[j] == '!')
{
sentences++;
}
}
printf("Letters: %i\n", letters);
printf("Words: %i\n", words + 1);
printf("Sentences: %i\n", sentences);
float L = ((float)letters / (float)words) * 100;
float S = ((float)sentences / (float)words) * 100;
float result = round(0.0588 * L - 0.296 * S - 15.8);
printf("%f\n", L);
printf("%f\n", S);
printf("%f\n", result);
if(result < 1)
{
printf("Before Grade 1");
}
if(result == 1)
{
printf("Grade 1");
}
if(result == 2)
{
printf("Grade 2");
}
if(result == 3)
{
printf("Grade 3");
}
if(result == 4)
{
printf("Grade 4");
}
if(result == 5)
{
printf("Grade 5");
}
if(result == 6)
{
printf("Grade 6");
}
if(result == 7)
{
printf("Grade 7");
}
if(result == 8)
{
printf("Grade 8");
}
if(result == 9)
{
printf("Grade 9");
}
if(result == 10)
{
printf("Grade 10");
}
if(result == 11)
{
printf("Grade 11");
}
if(result == 12)
{
printf("Grade 12");
}
if(result == 13)
{
printf("Grade 13");
}
if(result == 14)
{
printf("Grade 14");
}
if(result == 15)
{
printf("Grade 15");
}
if(result >= 16)
{
printf("Grade 16+");
}
printf("\n");
}
Text:
Congratulations! Today is your day. You're off to Great Places! You're off and away!
Result:
Letters: 65
Words: 14
Sentences: 4
500.000000
30.769232
4.000000
Grade 4
I need to calculate the '0.0588 * L - 0.296 * S - 15.8' formula in my code, but for some reason, it is giving me the wrong answer for some text and right for some text. in this particular example, it should give me 'Grade 3' but it is giving me 'Grade 4' instead and if I put a text for grade 10 it will give me 'Grade 10'. And the calculations for 'L' and 'S' are wrong, in this example, they should be L = 464.29 and S = 28.57. I really don't know where I am going wrong, can someone please help me?
The problem is that you count words by counting spaces, so you don't count the last word. You could solve the problem by initialising words
to 1.
Also I saw you noticed that problem since you wrote printf("Words: %i\n", words + 1);
so why in your calculations didn't you added 1? You print 14 as word count, but then you use 13 to calculate the average length of the words.
Anyway you should absolutely change the final prints with that
if(result < 16) {
printf("Grade %d\n", result);
}
else {
puts("Grade 16+");
}
Or even just
result < 16 ? printf("Grade %d\n", result) : puts("Grade 16+");