直方图格式

Histogram Formatting

本文关键字:格式 直方图      更新时间:2023-10-16

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

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

// 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()以正确格式化我的直方图。

假设所有数字都在[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;
    //...
}