What is the correct way to round offx, a float, to an int value?
Answer: A
Correct answer: y=(int)(x+0.5)
Adding 0.5 before truncating turns the cast's truncation into rounding: a fractional part of 0.5 or more carries the value past the next integer, while a smaller one does not.
The parentheses matter. (int)x + 0.5 casts first and then adds, so the 0.5 is never rounded away and the result is not an integer at all. And int(x+0.5) is C++ function-style casting, not valid C. Note the technique fails for negative values, where x - 0.5 would be needed, or round() from math.h.
Please log in or register to report this question.