Machine-translated by Google. Questions are authored in English.
Top

Discussion

What is the correct way to round offx, a float, to an int value?

  • A.y=(int)(x+0.5)
  • B.y=int(x+0.5)
  • C.y=(int)x+0.5
  • D.y=(int)(int)x+0.5)

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.

No comment is present. Be the first to comment.
Loading…

Post your comment

Please log in or register to post a comment.