首页 文章

std :: cout <<预测显示的任意双精度的自动字段宽度

提问于
浏览
0

我在控制台上显示了大量的双打,我想提前知道std :: cout将为给定的double显示多少小数位 . 这基本上是这样我可以在控制台中看起来很漂亮 . 例如(伪代码)

feild_width = find_maximum_display_precision_that_cout_will_use( whole_set_of_doubles );
...
// Every cout statement:
std::cout << std::setw( feild_width ) << double_from_the_set << std::endl;

我想cout“猜测”?基于双精度显示的精度很高 . 例如,它似乎显示

std::cout << sqrt(2) << std::endl;

如1.41421,还

std::cout << (sqrt(0.5)*sqrt(0.5) + sqrt(1.5)*sqrt(1.5)) << std::endl;

为2(而不是2.000000000000 ??????或1.99999999 ?????) . 好吧,也许这计算到2.0,但我不认为 sqrt(2) 会计算到1.41421,所以std :: cout必须做出一些关于在某个点显示多少小数位的决定,对吧?

无论如何可能预测这个以制定 find_maximum_display_precision...() 功能?

4 回答

  • 1

    有时C I / O咬人 . 制作漂亮的输出有时是其中之一 . C printf系列更易于控制,更易理解,更简洁,并且不会受到那些真正糟糕的ios :: global变量的困扰 . 如果由于其他原因需要使用C输出,则可以始终将sprintf / snprintf发送到字符串缓冲区,然后使用<< to stream运算符将其打印出来 . 恕我直言,如果你不需要使用C输出,不要 . 这是丑陋和冗长的 .

  • 0

    的std :: COUT ::精度();用它来确定精度示例:

    # include <iostream>
    # include <iomanip>
    
    int main (void) 
    {
    
       double x = 3.1415927
    
       std::cout << "Pi is " << std::setprecision(4) << x << std::endl;
       return 1;
    }
    

    这将显示:

    Pi is 3.142
    

    此链接还包括std :: cout :: precision(); http://www.cplusplus.com/reference/iostream/ios_base/precision/

  • 0

    在你的问题中,你正在混合精度和宽度,这是两个不同的事情 . 其他答案集中在精度上,但给定的精度是最大值,而不是显示的最小值 . 如果没有设置 ios::fixedios::scientific ,它不会填充尾随零 .

    这是一个确定用于输出的字符数的解决方案,包括10的符号和幂:

    #include <string>
    #include <sstream>
    #include <vector>
    
    size_t max_width(const std::vector<double>& v)
    {
      size_t max = 0;
    
      for (size_t i = 0; i < v.size(); ++i)
      {
        std::ostringstream out;
        // optional: set precision, width, etc. to the same as in std::cout
        out << v[i];
        size_t length = out.str().size();
        if (length > max) max = length;
      }
      return max;
    }
    
  • 2

    你需要的是固定的iomanip .

    http://www.cplusplus.com/reference/iostream/manipulators/fixed/

    double d = 10/3;
    
    std::cout << std::setprecision(5) << std::fixed << d << std::endl;
    

相关问题