【问题标题】:How to round a non-floating point number?如何舍入一个非浮点数?
【发布时间】:2015-02-16 09:10:58
【问题描述】:

如何对非浮点数进行四舍五入?例如9107609 降到 91 或者降到 911 等等。

【问题讨论】:

  • 9107609/1000009107609/10000
  • 我明白了。非常感谢:)

标签: c math numbers integer


【解决方案1】:

为了round,使用一半的加法(如果是正数,否则减去10000/2)

int rounded = (9107609 + 10000/2)/10000;

【讨论】:

    【解决方案2】:
    #include <math.h>
    
    //returns n rounded to digits length
    int round_int (int n, int digits)
    {
       int d = floor (log10 (abs (n))) + 1; //number of digits in n
    
       return floor(n / pow(10, d-digits));
    }
    

    【讨论】:

      【解决方案3】:

      floor(number/(10^numberofdigitstocut))ceil(number/(10^numberofdigitstocut)) 之类的就可以了。

      【讨论】:

        【解决方案4】:

        分别除以 100000 或 10000。 C 除法向零舍入,因此数字将始终向下舍入。要四舍五入到最接近的整数,请参阅this question

        【讨论】:

        • “四舍五入”是否等同于截断小数点?例如。 1.9 被“四舍五入”为 1?
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-06-09
        • 1970-01-01
        相关资源
        最近更新 更多