【问题标题】:Histogram Formatting直方图格式
【发布时间】:2014-01-19 16:27:09
【问题描述】:

我正在编写一个程序来从一个双精度数据数组创建一个水平直方图。我能够让程序显示每个子间隔的边界以及正确数量的星号。但是,数据未格式化。

这是负责输出的程序部分:

// endpoints == the boundaries of each sub-interval
// frequency == the number of values which occur in a given sub-interval
for (int i = 0; i < count - 1; i++)
{
    cout << setprecision(2) << fixed;
    cout << endPoints[i] << " to " << endPoints[i + 1] << ": ";
    for (int j = frequency[i]; j > 0; j--)
    {
        cout << "*";
    }
    cout << " (" << frequency[i] << ")" << endl;
}

我的输出如下所示:

0.00 to 3.90: *** (3)
3.90 to 7.80: * (1)
7.80 to 11.70: * (1)
11.70 to 15.60:  (0)
15.60 to 19.50: ***** (5)

这是我想要的样子:

00.00 to 04.00: *** (3)
04.00 to 08.00: * (1)
08.00 to 12.00: * (1)
12.00 to 16.00:  (0)
16.00 to 20.00: ****** (6)

我查阅了 C++ 语法并找到了 setw() 和 setprecision() 之类的东西。我尝试使用两者来格式化我的直方图,但无法让它看起来像模型。我希望有人能告诉我我是否走在正确的轨道上,如果是这样,如何实现 setw() 和/或 setprecision() 以正确格式化我的直方图。

【问题讨论】:

    标签: c++ format histogram


    【解决方案1】:

    假设所有数字都在 [0,100) 区间内,您想要的是一个操纵器链,例如:

    #include <iostream>
    #include <iomanip>
    
    int main() {
        std::cout
            << std::setfill('0') << std::setw(5)
            << std::setprecision(2) << std::fixed
            << 2.0
            << std::endl;
    
        return 0;
    }
    

    将输出:

    02.00
    

    这是一个单一的值,您可以轻松地调整它以满足您的需求。

    例如,您可以将其转换为运算符并像这样使用它:

    #include <iostream>
    #include <iomanip>
    
    class FixedDouble {
    public:
        FixedDouble(double v): value(v) {}
        const double value;
    }
    
    std::ostream & operator<< (std::ostream & stream, const FixedDouble &number) {
        stream
            << std::setfill('0') << std::setw(5)
            << std::setprecision(2) << std::fixed
            << number.value
            << std::endl;
    
        return stream;
    }
    
    int main() {
        //...
    
        for (int i = 0; i < count - 1; i++) {
            std::cout
                << FixedDouble(endPoints[i])
                << " to "
                << FixedDouble(endPoints[i + 1])
                << ": ";
        }
    
        for (int j = frequency[i]; j > 0; j--) {
            std::cout << "*";
        }
        std::cout << " (" << frequency[i] << ")" << std::endl;
    
        //...
    }
    

    【讨论】:

    • 我的直方图需要能够处理所有实数。机械手还能做到这一点吗?
    • 嗯,是的,您只需要调整 setw 值,这是打印的字符总数(包括填充零/空格和小数点)和 setprecision 值,这是要保留的小数位数。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-15
    • 2013-07-18
    相关资源
    最近更新 更多