Untitled
unknown
plain_text
a month ago
3.2 kB
30
Indexable
Never
#include <cs50.h> #include <ctype.h> #include <math.h> #include <stdio.h> #include <stdlib.h> #include <string.h> string calculateGradeLevel(int letters, int words, int sentences); int numOfLetters(string text, int length); int numOfWords(string text, int length); int numOfSentences(string text, int length); float averagePer100Words(char averageOf, int letters, int words, int sentences); // command line arguments appropriate here int main(int argc, string argv[]) { string text = get_string("\nText: "); int length = strlen(text); int letters = numOfLetters(text, length); int words = numOfWords(text, length); int sentences = numOfSentences(text, length); string gradeLevel = calculateGradeLevel(letters, words, sentences); printf("%s\n", gradeLevel); } string calculateGradeLevel(int letters, int words, int sentences) { // *approximate* grade level // formula: index = 0.0588 * L - 0.296 * S - 15.8 // L = avg num of letters per 100 words // S = avg num of sentences per 100 words float L = averagePer100Words('L', letters, words, sentences); float S = averagePer100Words('S', letters, words, sentences); float index = 0.0588 * L - 0.296 * S - 15.8; string gradeLevel; int roundedIndex = roundf(index); if (roundedIndex >= 16) { gradeLevel = "Grade 16+"; } else if (roundedIndex < 1) { gradeLevel = "Before Grade 1"; } else { char *buffer = malloc(50 * sizeof(char)); sprintf(buffer, "Grade %i", roundedIndex); gradeLevel = buffer; // when the buffer gets out of this method's scope into main, the // output is "i". check why. // FIXED. allocated memory. } return gradeLevel; } int numOfLetters(string text, int length) { int letters = 0; for (int i = 0; i < length; i++) { if (isalpha(text[i]) != 0 && text[i] != '-' && text[i] != 96 && text[i] != 39) // is a letter { letters++; } } return letters; } int numOfWords(string text, int length) { int words = 1; // numOfSpaces + 1 = numOfWords for (int i = 0; i < length; i++) { if (isspace(text[i])) { words++; } if (text[i] == '-') { words--; } } return words; } int numOfSentences(string text, int length) { int sentences = 0; for (int i = 0; i < length; i++) { if (ispunct(text[i]) != 0 && text[i] != ',' && text[i] != '"' && text[i] != '-' && text[i] != 96) { sentences++; } } return sentences; } float averagePer100Words(char averageOf, int letters, int words, int sentences) { // calculate letter average or sentence average (per 100 words) float average; if (strchr(&averageOf, 'L')) { average = (100.0 * (float) letters) / (float) words; return average; } else if (strchr(&averageOf, 'S')) { average = (100.0 * (float) sentences) / (float) words; return average; } return 0; }
Leave a Comment