DrJessop
DrJessop

Reputation: 472

Conditional Not Following Instructions in C

I made a program that accepts up to and including 21 inputs of grade data and outputs the number of marks, the max and min, the standard deviation, and the letter grades. Thus, I made an array of size 21. Unfortunately, all of the loops in my program continue until array[i] != '\0', and I didn't know that 0 is equivalent to null, so it was originally quite broken for when people entered 0. To fix this problem, I said that if you enter 0, the array at that particular index instead is assigned 0.000001. This solved most of my problems, with the exception of my maxMin function, which for some reason still prints 0.000001 as the min mark. This function is seen below...

void maxMin() {
  float min = array[0];
  float max = array[0];
  for (int j = 1; array[j] != '\0'; j++) {
    if (min > array[j]) {
      min = array[j];
    }
    if (max < array[j]) {
      max = array[j];
    }
  }
  printf("The highest mark is: %f \n", max);
  if (min == 0.000001) {
    printf("The lowest mark is: 0 \n");
  }
  else {
    printf("The lowest mark is: %f \n", min);
  }
}

How can I get this function to print 0 as the min mark?

Upvotes: 1

Views: 116

Answers (2)

user3629249
user3629249

Reputation: 16540

As another answer stated:

if (min == 0.000001) 

is the source of the problem.

However, adding the 'F' suffix is not the whole answer.

The whole answer is that comparing float or double values will (usually) fail because many/most numbers cannot be exactly represented in float or double

However, the posted code has some other problems, like the comparison of a float to a char when trying to determine if at end of numbers. Strongly suggest revising the process of inputting the 21 numbers so the code keeps track of how many numbers were input and pass that count to the minmax() function.

Upvotes: 0

H.S.
H.S.

Reputation: 12679

The problem is this statement:

if (min == 0.000001) {

0.000001 will be treated as double. The decimal number 0.000001 is represented differently as a single-precision float and as a double-precision double.

You need to put suffix f with float literal:

if (min == 0.000001f) {

When you put f suffix, it tells the compiler that this is a float.

Upvotes: 1

Related Questions