Readability for cs50. There valuable changes for no reason at "if" line

Viewed 110

So I started programming 5 days ago. I'm going through course cs50. There is a task (see https://cs50.harvard.edu/x/2020/psets/2/readability/) to make a program which evaluates grade of text. I did it.

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

int main(void) {
  int ln = 0;
  int wn = 1;
  int sn = 0;
  string text = get_string("write your text:\n");
  int l = strlen(text);
  for (int i = 0; i < l; i++) {
    if (isalpha(text[i])) {
      ln++;
    }
    if ((char) (text[i]) == (char) (' ')) {
      wn++;
    }

    if ((char) (text[i]) == (char) ('.') | (char) (text[i]) == ('!')
        | (char) (text[i]) == ('?')) {
      sn++;
    }
  }
  float grade = ((float) ((ln / wn * 100) * 0.0588)
      - ((float) ((sn / wn * 100) * 0.296)) - 15.8);

  if (grade > 1 && grade < 16) {
    printf("Grade %f\n", grade);
  } else if (grade < 1) {
    printf("Before grade 1\n");
  } else if (grade > 16) {
    printf("grade 16+\n");
  }

  printf("%i, %i, %i", ln, wn, sn);
}

And when I uses debugger, I can see that at that long line, where I do all the math, float grade is equal just to the number I need, everything is fine. But right after it, where "if" starts, it becomes 1.8 for no reason. I tried to change different parameters, and the math is still right till the if line. What do I do wrong?

1 Answers

Code at least has this problem: Nothing printed when grade is 1 or 16

  // Nothing printed when grade is 1 or 16
  if (grade > 1 && grade < 16) {
    printf("Grade %f\n", grade);
  } else if (grade < 1) {
    printf("Before grade 1\n");
  } else if (grade > 16) {
    printf("grade 16+\n");
  }

Suggest

  //        >=            <=
  if (grade >= 1 && grade <= 16) {
    printf("Grade %f\n", grade);
  } else if (grade < 1) {
    printf("Before grade 1\n");
  } else {
    printf("grade 16+\n");
  }

Integer division likely wrong. Use FP division.

//                          vvvvvvv                               vvvvvvv 
// float grade = ((float) ((ln / wn * 100) * 0.0588) - ((float) ((sn / wn * 100) * 0.296)) - 15.8);
float grade = 0.0588 * ln / wn * 100 - 0.296 * sn / wn * 100 - 15.8;

Improvements

// if ((char) (text[i]) == (char) (' ')) {
if (text[i] == ' ') {

// if ((char) (text[i]) == (char) ('.') | (char) (text[i]) == ('!') | (char) (text[i]) == ('?')) {
if (text[i] == '.' || text[i] == '!' || text[i] == '?') {
Related