简体   繁体   中英

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM