【发布时间】:2023-03-07 10:59:01
【问题描述】:
我有一个类的数据成员需要四舍五入为 2 位整数,而与输入位数无关。
例如:
roundUpto2digit(12356463) == 12
roundUpto2digit(12547984) == 13 // The 5 rounds the 12 up to 13.
目前我的代码如下:
int roundUpto2digit(int cents){
// convert cents to string
string truncatedValue = to_string(cents);
// take first two elements corresponding to the Most Sign. Bits
// convert char to int, by -'0', multiply the first by 10 and sum the second
int totalsum = int(truncatedValue[0]-'0')*10 + int(truncatedValue[1]-'0');
// if the third element greater the five, increment the sum by one
if (truncatedValue[2]>=5) totalsum++;
return totalsum;
}
任何使它不那么难看的建议将不胜感激。
【问题讨论】:
-
这对codereview.stackexchange.com 来说可能是一个更好的问题。
-
你不喜欢你的代码的什么地方?我认为这很清楚,不认为你会得到比这 3 行短得多
-
@tobi303 转换较少的东西(按位运算等)?
标签: c++ integer truncation