我有一个数据成员的类,需要四舍五入为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](http://codereview.stackexchange.com)更好的问题。 – 2015-03-31 12:48:08
什么是你不喜欢你的代码?我认为这很清楚,不认为你会比这3行 – user463035818 2015-03-31 12:49:55
@ tobi303短得多,而转换次数少(按位操作等)? – Ziezi 2015-03-31 12:54:39