Discussion
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.
No comment is present. Be the first to comment.
Loading…
Post your comment
Please log in or register to post a comment.
Examination Categories
- SSC Exams
- Banking Exams
- Teaching Exams
- Civil Services Exams
- Railways Exams
- Engineering Recruitment Exams
- Defence Exams
- State Government Exams
- Police Exams
- Insurance Exams
- Nursing Exams
- Other Government Exams
- NRA CET
- PG Entrance Exams
- Campus Placement
- MBA Entrance Exams
- CUET and UG Entrance
- Judiciary Exams
- Regulatory Body Exams
- Software Development