integer division, rounding

时光毁灭记忆、已成空白 提交于 2020-02-29 07:39:05

问题


There is integer variable, voltage in millivolts.

signed int voltage_mv = 134; //134mV

I have 2-segment display and I want to display hundredths of volts.

How can I convert milivolts to hundredths volts in one operation? Without IF statement, without function?

134 => 13
135 => 14

回答1:


How about simple rounding:

int millivoltToDisplay (int millivolts)
{
  return (millivolts+5)/10;
}

(written as a function for clarity)




回答2:


For the same of completeness, if the denominator is odd, then instead of doing:

return (millivolts+denominator/2)/denominator;

you can just have

return (2*millivolts+denominator)/(2*denominator);

and get the correct rounding.



来源:https://stackoverflow.com/questions/4085239/integer-division-rounding

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!