我有一个带有数据成员的类,无论输入数字的数量如何,都需要向上舍入为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;
}
任何让它不那么丑陋的建议都将深受赞赏。
答案 0 :(得分:1)
你可以使用固定点整数算术,它可能更快,看起来更好。您希望数字的大小为 10 ^ 2 ,并且您也可以使用10的任意比例幂,所以要圆整,您只需要应用公式:
ROUNDED_VAL = (INITIAL_VAL + (10^(ORIG_SCALE - 2) / 2)) / 10^(ORIG_SCALE - 2)
所以你的代码看起来像这样:
int roundUpto2digit(int cents){
int scale = 10;
while(cents / scale > 0) {
// Find out original scale. This can be done maybe faster with a divide and conquer algorithm
scale *= 10;
}
int applied_scale = scale / 100;
if (applied_scale == 0) {
// In case there is only one digit, scale it up to two
return 10 * cents;
}
return ((cents + (applied_scale / 2)) / applied_scale);
}
编辑:我写的10 * cents
行是根据我的解释对我所提出的问题进行的任意推断。如果这不是理想的行为,那么它当然可以改变。
答案 1 :(得分:0)
#include <math.h>
int roundUpto2digit(int value)
{
value /= pow(10,(int)log10(value)-2);
/*
(int)log10(value) returns base ten logarithm (number of digits of your number)
pow(10, N) returns number 1 followed by N zeros
example:
pow(10,(int)log10(123)-2) returns 1
pow(10,(int)log10(1234)-2) returns 10
pow(10,(int)log10(1234567)-2) returns 10000
thus
value / pow(10,(int)log10(value)-2) returns first 3 digits
*/
return value%10>=5? (value+10)/10 : value/10;
/*
if(value%10>=5)// the last digit is >= 5
{
// increase previous number
value = value + 10;
}
// return number without the last digit
return value/10;
*/
}