【问题标题】:Truncating integer using string manipulation?使用字符串操作截断整数?
【发布时间】: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


【解决方案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 行是我根据我的解释提出的问题的任意推断。如果这不是所需的行为,当然可以更改。

【讨论】:

    【解决方案2】:
    #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;
        */
    }
    

    【讨论】:

    • 也许可以解释一下您是如何得出这个答案的?那是返回线中的一个严重的 1 线,所以可以概述它的作用吗?
    猜你喜欢
    • 2014-07-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-14
    • 2015-12-14
    相关资源
    最近更新 更多