开发者

integer division, rounding

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


How about simple rounding:

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

(written as a function for clarity)


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜