0

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;
}
Flair
  • 2,609
  • 1
  • 29
  • 41

1 Answers1

1
 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;
Gopi
  • 19,784
  • 4
  • 24
  • 36
  • Did I not initialize by using float y? Would I need float y = 0.0? – Flair Dec 01 '14 at 04:55
  • 1
    @Flair Yes `float y;` is just declaration you need to have a initialization like `y =0;` – Gopi Dec 01 '14 at 04:56
  • In C, you have to specifically give the variable an initial value before start using it. In other languages, some will automatically initialize to 0.0 and some will issue compiler error. – fang Dec 01 '14 at 07:07