#include <cs50.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <math.h>
//preload variables.
float S, L;
int get_sent(string text);
int get_words(string text);
int get_letter(string text);
int get_words(string text);
int main(void)
{
//get Text to be analyzed from user.
string text = get_string("Text: ");
//get the number of letters within text.
int letters = get_letter(text);
//get the number of words within text.
int words = get_words(text);
//get the number of sentences within the text.
int sent = get_sent(text);
// MATHS
S = sent / words * 100; <---- RIGHT HERE!!! when tested S = 0.00000 no matter what.
L = letters / words * 100;
float index = (0.0588 * L) - (0.296 * S) - 15.8;
int grade = round(index);
if (grade < 1)
{
printf("Before Grade 1\n");
}
if (grade > 1 && grade < 16)
{
printf("Grade %i\n", grade);
}
if (grade > 16)
{
printf("Grade 16+\n");
}
//print text back to user, // this after testing.
printf("%s\n", text);
//print how many letters were typed back to user, // this after testing.
printf("%i Letters\n", letters);
//print how many words were typed back to user, // this after testing.
printf("%i Words\n", words);
//print how many sentences were typed back to user, // this after testing.
printf("%i Sentences\n", sent);
//print index as a float for testing, // this after testing.
printf("index = %f\n", index);
// Print grade int after float index was rounded, // this after testing.
printf("grade = %i\n", grade);
printf("S = %f\n", S);
printf("L = %f\n", L);
}
//get the amount of letters used in the string counting only a-z and A-Z, no spaces or special
chars.
int get_letter(string text)
{
int letter = 0;
//count the letter in the string from user and count only upper and lowercase letters all = 1
"point" per letter.
for (int i = 0, len = strlen(text); i < len; i++)
{
//count the letters a-z && A-Z.
if (isalpha(text[i]))
{
//add a "point" to letter.
letter++;
}
}
//return "points" back to main.
return letter;
}
int get_words(string text)
{
int word = 1;
for(int i = 0, len = strlen(text); i < len; i++)
{
if (isspace(text[i]))
{
word++;
}
}
return word;
}
int get_sent(string text)
{
int sent = 0;
for (int i = 0, len = strlen(text); i < len; i++)
{
if (text[i] == 46 || text[i] == 33 || text[i] == 63 )
{
sent++;
}
}
return sent;
}
With testing my code S = 0.000 No matter what is entered. return sent returns the correct amount of sentences but when I S = sent / words *100; it doesn’t seem to use the return to load sent correctly and I’ve bashed my face into the keyboard for an hour trying to figure out why. I’m done other then that.
>Solution :
In your code
S = sent / words * 100;
will perform integer arithmetic, as all involving operands are int. If you need a floating point arithmetic, you need to enforce it. Something like
S = sent / (float) words * 100;
Same goes for other statements, too.