开发者

integer division, rounding

开发者 https://www.devze.com 2023-01-23 10:59 出处:网络
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.

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

精彩评论

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

关注公众号