c++ - 使用字符串操作截断整数?

标签 c++ integer truncation

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

任何让它不那么难看的建议都将不胜感激。

最佳答案

您可以使用定点整数算法,它可能更快并且看起来更好。您需要 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 行是我根据自己的解释对问题做出的任意推断。如果这不是所需的行为,当然可以更改。

关于c++ - 使用字符串操作截断整数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29368963/

相关文章:

swiftui - SwiftUI Text View 的截断问题

c++ - 使 vector 3D 从 vector AND 派生,需要保留字段 x y z

c++ - fasttext 断言 "counts.size() == osz_"失败

netcdf - 截断 netCDF

c++ - 递归地将整数存储在数组中

Java Integer compareTo() - 为什么使用比较与减法?

c++ - 线程安全,在C++中有序映射/哈希?

c++ - 级联 NavigationPane : connect to an object signal into another qml file

python - 在 Python 中计算最多两位小数