【问题标题】:Need my output to be in this form XXX.XXX c++需要我的输出采用这种形式 XXX.XXX c++
【发布时间】:2014-02-24 00:27:02
【问题描述】:

例如,我得到一个三角形的面积为 6,我需要我的输出显示 006.000

我知道 setprecision 可以将小数位限制为三位,但我如何在我的解决方案前面放置零?

这就是我所拥有的

CTriangle Sides(3,4,5);

cout << std::fixed << std::setprecision(3);

cout << "\n\n\t\tThe perimeter of this tringle is   = " << Sides.Perimeter();

cout << "\n\n\t\tThe area of the triangle is        = " << Sides.Area();

cout << "\n\n\t\tThe angle one is                   = " << Sides.Angleone();

cout << "\n\n\t\tThe angle two is                   = " << Sides.Angletwo();

cout << "\n\n\t\tThe angle three is                 = " << Sides.Anglethree();

cout << "\n\n\t\tThe altitude one of the triangle   = " << Sides.Altitudeone();

cout << "\n\n\t\tThe altitude two of the triangle   = " << Sides.Altitudetwo();

cout << "\n\n\t\tThe altitude three of the triangle = " << Sides.Altitudethree();

输出为

            The perimeter of this triangle is   = 12.000

            The area of the triangle is        = 6.000

            The angle one is                   = 90.000

            The angle two is                   = 36.870

            The angle three is                 = 53.130

            The altitude one of the triangle   = 2.400

            The altitude two of the triangle   = 6.667

            The altitude three of the triangle = 3.750

但无论我的解决方案是什么,我都需要以 XXX.XXX 形式给出所有答案。(因为值会改变)

感谢任何帮助,谢谢!

【问题讨论】:

    标签: c++ math formatting significant-digits


    【解决方案1】:

    使用可以使用paddingfilling操纵器:

    std::setfill('0');             // is persistent
    //...
    
    cout << std::setw(7) << value; // required for each output
    

    【讨论】:

    • 记得还要设置fixedprecision
    【解决方案2】:

    使用iomanip 中的std::internalstd::fixedstd::setfillstd::setwstd::setprecision 以及相关标头,您可以:

    std::cout << std::fixed << std::setfill('0') << std::internal << std::setprecision(3);
    
    std::cout << std::setw(7);
    std::cout << 12.34f << "\n";
    

    并获得所需的输出。 See it live on Coliru!

    【讨论】:

      【解决方案3】:

      【讨论】:

        【解决方案4】:

        printf 函数可以做到这一点,您可以查看文档: http://www.cplusplus.com/reference/cstdio/printf/

        您的情况有些独特,因为: (这些不是完整的代码sn-ps,抱歉)

        精度仅适用于浮点格式:

        $ printf("%03.3f\n", 6)
        > 6.000
        

        而左填充仅适用于整数格式:

        $ printf("%03.3d\n", 6)
        > 006
        

        祝你好运,希望你能从这里拿走它

        【讨论】:

        • printf 函数来自 C,虽然可用,但与 C++ 混合被认为不好。
        • “认为不好” - 更具体地说,它们是独立缓冲的,因此每次在使用printf() 写入一些内容和写入std::cout 之间切换时,都需要显式刷新。无论如何 +1 - 这很方便,boost format 使用模糊的 printf 类似符号,以便以更加 C++ 感知的方式进行格式化。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-08-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-07-24
        相关资源
        最近更新 更多