【问题标题】:Dropping extra decimal places in c在c中删除额外的小数位
【发布时间】:2013-03-03 03:07:24
【问题描述】:

我遇到了一个小问题。我正在尝试删除 c 中多余的小数位,这将用于计算。

例如 67.98345, 我希望它是 67.98

但不仅仅是用于 printf 语句。我需要双精度为 67.98 而不是 67.98345

【问题讨论】:

  • “我需要双倍实际上是 67.98” 你有麻烦了。

标签: c double decimal extra


【解决方案1】:

@mvp 的回答还可以,但有一个小问题。如果 x 接近最大 double 幅度,则乘法的中间值可能会溢出 double。解决此问题的替代方法是:

double intpart, fracpart;

fracpart = modf(x, &intpart);
x_rounded = intpart + round(fractpart * 100) / 100;

【讨论】:

    【解决方案2】:

    这将四舍五入到最接近的值:

    double x_rounded = round(x*100)/100;
    

    为了完整起见,这些将向下或向上取整:

    double x_rounded_down = floor(x*100)/100;
    double x_rounded_up   = ceil (x*100)/100;
    

    【讨论】:

    • 请注意,您必须#include <math.h> 才能正确,并且如果 x 接近最大双倍量值,则中间结果可能会溢出,因此答案将为 +-inf。跨度>
    • 考虑到最大 double 值是 1.7977e+308,只有在 x > 1.7977e+306 时才会遇到这个问题 - 大多数人都可以
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多