-1

Getting some weird results from printf.

double scale = 129 / 1024;

printf("%f \n", scale);

is printing either -0.000000, 0.000000 or some huge random number like 947634637338383939387378370000000000000.00000. It seems to randomly alternate between these each time i compile and run. There is a lot more to the program, but i can't figure out what could possibly be affecting printf in this situation. This is exactly how these two statements appear in my program. What have i done?

Rob Allsopp
  • 3,309
  • 5
  • 34
  • 53
  • I'm not so sure that this is technically a duplicate question. It could be a `printf`-related issue though I personally believe that it is a case of `int` division coerced to floating point. – D.Shawley Aug 06 '13 at 00:05
  • @Kyle_the_hacker: That wouldn't be the case for a `double` variable tho. It wouldn't surprise me if that's an uninitialized value. – Mats Petersson Aug 06 '13 at 00:21
  • 1
    "%f" takes a float, not a dobule. – kfsone Aug 06 '13 at 03:06

2 Answers2

0

I would expect it to print 0.000000 all of the time. (129 / 1024) = 0 for integer arithmetic.

D.Shawley
  • 58,213
  • 10
  • 98
  • 113
  • 2
    And how do you explain the other values he get? – Ran Eldan Aug 05 '13 at 23:59
  • I honestly don't know. I'm pretty sure that there is additional code not being shown or something of the like. `double d = 129 / 1024` will *always* produce a value of zero. – D.Shawley Aug 06 '13 at 00:04
0

Printing zero not erratic behaviour, it's showing you the result of the division of 129/1024, and since both those numbers are integers, the result is 0. This is then assigned to the double.

Fix that problem by changing 129 to 129.0, which makes it a double value.

The "large number" can't be explained from the code we can see. I'm guessing that there is MORE code than these two lines however, and there is probably something going wrong elsewhere that affects the result.

Mats Petersson
  • 126,704
  • 14
  • 140
  • 227