【发布时间】:2016-02-28 23:44:39
【问题描述】:
我一直在编写代码来生成水平直方图。该程序将用户输入的任何数字范围转换为向量。然后它会询问用户他们希望直方图开始的最低值,以及他们希望每个 bin 有多大。例如:
如果lowestValue = 1 和binSize = 20
并且向量填充了值{1, 2, 3, 20, 30, 40, 50},它会打印出如下内容:
(bin) (bars) (num)(percent)
[ 1-21) #### 4 57%
[21-41) ## 2 28%
[41-61) ## 2 28%
这是执行此操作的大部分代码:
void printHistogram(int lowestValue, int binSize, vector<double> v)
{
int binFloor = lowestValue, binCeiling = 0;
int numBins = amountOfBins(binSize, (int)range(v));
for (int i = 0; i<=numBins; i++)
{
binCeiling = binFloor+binSize;
int amoInBin = amountInBin(v,binFloor, binSize);
double perInBin = percentInBin(v, amoInBin);
if (binFloor < 10)
{
cout << "[ " << binFloor << '-' << binCeiling << ") " << setw(20) << left << formatBars(perInBin) << ' ' << amoInBin << ' '<< setprecision(4) << perInBin << '%' << endl;
binFloor += binSize;
}
else
{
cout << '[' << binFloor << '-' << binCeiling << ") " << setw(20) << left << formatBars(perInBin) << ' ' << amoInBin << ' '<< setprecision(4) << perInBin << '%' << endl;
binFloor += binSize;
}
}
}
以及计算每个 bin 中有多少项的函数:
int amountInBin(vector<double> v, int lowestBinValue, int binSize)
{
int count = 0;
for (size_t i; i<v.size(); i++)
{
if (v[i] >= lowestBinValue && v[i] < (lowestBinValue+binSize))
count += 1;
}
return count;
}
现在我的问题:
由于某种原因,它没有计算 20-40 之间的值。至少从我的测试中可以看出。这是跑步的图像:
感谢任何帮助。
【问题讨论】:
标签: c++ output runtime-error histogram