【问题标题】:Using streams to print max amount of decimal places after dot使用流打印点后的最大小数位数
【发布时间】:2012-11-01 22:48:30
【问题描述】:

如何使用 stringstream 打印双数点后的 max 个小数位数(无尾随零且无舍入)?例如,如果我只想打印最多 5 个小数位:

1 -> 1
1.23 -> 1.23
1.234 -> 1.234
1.2345 -> 1.2345
1.23456 -> 1.23456
1.234567 -> 1.23456
1.2345678 -> 1.23456
1230.2345678 -> 1230.23456 <- Demonstrating that I am not talking about significant digits of the whole number either

等等

在我看到的所有工具(setw、setprecision、fixed 等)中,我似乎无法弄清楚这一点。谢谢!

【问题讨论】:

  • 一般没有这种东西。例如,当转换为二进制浮点数时,1.1 将作为重复数字结束。你上面给出的大多数数字只能近似为浮点数,代码基本上不可能猜测存储的 1.22999999997 是否真的是你想要的,或者它最初是 1.23而是。
  • 非常大或非常小的数字呢?喜欢1.0003e-15 == 10.003e-14

标签: c++ stream


【解决方案1】:

您是否绝对要使用 stringstream 选项执行此操作?

您可以像这样编写round 函数:

double round(double n, int digits) {
    double mult = pow(10, digits);
    return floor(n*mult)/mult;
}

然后打印round(1.2345678, 5)

【讨论】:

    【解决方案2】:

    没有内置的方法可以做到这一点(据我所知)。然而,像下面这样的 hack 是可能的:

    void print_with_places(double num, unsigned places) {
       for (double i = 1; i < num; i*=10) { //have to use a double here because of precision...
          ++places;
       }
       std::cout << std::setprecision(places) << num;
    }
    

    这不是最漂亮的,但就是这样或将其打印到字符串然后操作字符串。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-15
      • 2014-06-10
      • 1970-01-01
      • 2017-05-04
      • 1970-01-01
      相关资源
      最近更新 更多