2015-03-31 47 views
0

我有一个数据成员的类,需要四舍五入为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; 
} 

任何建议,使其不太难看会深深感激。

+1

这可能是[codereview.stackexchange.com](http://codereview.stackexchange.com)更好的问题。 – 2015-03-31 12:48:08

+0

什么是你不喜欢你的代码?我认为这很清楚,不认为你会比这3行 – user463035818 2015-03-31 12:49:55

+0

@ tobi303短得多,而转换次数少(按位操作等)? – Ziezi 2015-03-31 12:54:39

回答

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行我写的是我根据我的理解对这一问题进行任意推断。如果这不是理想的行为,那当然可以改变。

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; 
    */ 
} 
+0

也许解释你如何到达这个答案?这是一个严重的回报线,所以可能概述了它的作用? – Pseudonym 2015-03-31 13:29:12