# redondear al 1/16 más cercano y truncar al 1/16 más cercano de un valor en C

Suppose size of a block is 1X1 and I have to move in steps of 1/16 along both the x and y direction. I want to round 0.53124 to the nearest 1/16 of the size of the block which is 0.5625. And similarly I want to truncate 0.53124 to the nearest 1/16 of the size of the block which is 0.5. Is there an efficient way of doing this? Please let me know.

preguntado el 10 de marzo de 12 a las 16:03

What language are you using? This can be helpfull. -

Thanks for reminding me. Please use C. Thanks. -

## 2 Respuestas

Simplest way in most situations and languages would to be to

• multiplicar por 16
• round to the nearest integer
• dividir por 16.

respondido 10 mar '12, 16:03

Even simpler, and often a better approach to this sort of problem, is to define a block to be 16x16 and do all work in 16ths. - Marca de alto rendimiento

And since 16 is a power of 2, accuracy won't suffer unless there's an overflow. - Ignacio Vázquez-Abrams

Since you seem to want punto fijo, I would simply use fixed point (integers in units of 1/16) if possible. But if you really need to mix with floating point operations and round, one way is to parcialidad all your values by a huge number such that the 1/16 place is the last place. Unfortunately with gcc, this approach can have problems on systems like i387 where floating point expressions are evaluated with extra precision, unless you're already using `long double` everywhere, so from a practical standpoint, Joachim's answer may be easier to make reliable (although it probably performs much worse).

respondido 10 mar '12, 21:03

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.