Not sure why C prints out NaN

856 Views Asked by At

I was coding up a short program to compute right endpoints for a given graph (not shown here), so to avoid tedious computation, I decided to write up a short program to do the work for me. Yet my C program just prints out nan. I am very rusty on C, but I am not sure why I am getting NaN.

#include <stdio.h>

int main(void) {
    int x;
    float y, z;
    for (x = 0; x <= 8; x++) {
        y += 10.0 - (12.0 + (float)x) / 4.0;
        printf("%f\n", y);
    }
    z = 0.5 * y;
    printf("%f\n", z);
    return 0;
}
1

There are 1 best solutions below

3
On BEST ANSWER
 y = 10.0 - (12.0 + (float)x) / 4.0;

Followed by

y = y+1;

This makes sense else you have y uninitialized which leads to undefined behavior because the value of y is undeterminate. During declaration you can initialize y and use += operator.

Like

float y = 0;