Basic and Advance C Question:

How do I round numbers?

Tweet Share WhatsApp

Answer:

The simplest and most straightforward way is with code like
(int)(x + 0.5)
C's floating to integer conversion truncates (discards) the fractional part, so adding 0.5 before truncating arranges that fractions >= 0.5 will be rounded up. (This technique won't work properly for negative numbers, though, for which you could use something like (int)(x < 0 ? x - 0.5 : x + 0.5), or play around with the floor and ceil functions.)
You can round to a certain precision by scaling:
(int)(x / precision + 0.5) * precision
Handling negative numbers, or implementing even/odd rounding, is slightly trickier.
Note that because truncation is otherwise the default, it's usually a good idea to use an explicit rounding step when converting floating-point numbers to integers. Unless you're careful, it's quite possible for a number which you thought was 8.0 to be represented internally as 7.999999 and to be truncated to 7.

Download C Programming PDF Read All 221 C Programming Questions
Previous QuestionNext Question
Why does not C have an exponentiation operator?I am sure I have got the trig functions declared correctly, but they are still giving me wrong answers.