【问题标题】:C Program using a function to round a floating- point number to 3 digits after the decimal? [closed]C 程序使用函数将浮点数舍入到小数点后 3 位? [关闭]
【发布时间】:2016-10-18 15:52:37
【问题描述】:

例如,如果输入是 3456.7856,那么输出应该是 3456.786。

非常感谢您,祝您有美好的一天!

【问题讨论】:

  • 您不会对变量执行此操作,而是在使用 printf 格式化输出时执行此操作。
  • 您要对输出进行四舍五入,还是将四舍五入的值赋给变量?
  • round_x = round(x * 1000.0) / 1000.0; 由于大多数浮点实现无法准确表示小数,因此结果可能不准确。

标签: c math rounding


【解决方案1】:

名为printf 的标准库函数可以进行舍入:

#include <stdio.h>

int
main(void) {
    double dbl = 3456.7856;
    printf("%.3f", dbl);
}

如果您想在某些计算中使用舍入值:

#include <stdio.h>
#include <float.h>
#include <math.h>

double
round_to_3(double dbl);

int
main(void) {
    double dbl = 3456.7856, dummy; // dummy will hold the integral part of dbl
                                   // , which we won't use

    if(modf(dbl, &dummy)) {
        dbl = round_to_3(dbl);
    }

    // Do some computation

    printf("%.3f", dbl);
}

double
round_to_3(double dbl) {
    char buffer[1 + 1 + DBL_MAX_10_EXP + 1 + 3 + 1]; 
    // Making sure the buffer is big enough:
    //
    // 1 for the potential sign
    // plus 1 for the leading digit
    // plus DBL_MAX_10_EXP for the potential digits before the decimal mark
    // plus 1 for the decimal mark
    // plus 3 for the digits after the decimal mark
    // plus 1 for the ending '\0'

    sprintf(buffer, "%.3f", dbl);
    sscanf(buffer, "%lf", &dbl);

    return dbl;
}

这个解决方案看起来很奇怪,但它不会导致溢出,并且提供了最大的准确性。

modf(dbl, &amp;intpart) == 0 时不需要进行四舍五入,因为通常与base ^ exponent 相比,显着性非常小,即在这种情况下10 ^ DBL_MAX_10_EXP。(这里,^ 表示取幂,而不是按位异或)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多