嵌套for循环不正常

时间:2016-04-11 03:06:59

标签: c++ for-loop nested-loops

我有一段代码应该生成一个直方图,给定一些输入,如下所示。

ostream& operator<<(ostream& outputStream, aHistogram& h){
outputStream << "Constructing histogram." << endl;
int numberOfBins = h.v.size();
int max = h.getMax();
int longest = h.getLongestLine();
int diceData = 0;

for (int i = 0; i < numberOfBins; ++i) {
    outputStream << i + h.getNumDice() << ":";
    diceData = h.v.at(i);

    for (int x = 1; x <= (diceData / max) * longest; x++) {
        outputStream << "X";
    }
    outputStream << endl; 
}

return outputStream;}

问题是,它只生成&#34; max&#34;最高值输入的X的数量,并且对于其他值,循环似乎根本不起作用。这是输出的屏幕截图。

我不确定这里出了什么问题。

1 个答案:

答案 0 :(得分:0)

(diceData / max) * longest

使用整数数学,除法向下舍入为0,在0 * longest时最终得到diceData < max。使用浮点数学来获得0到1之间的数字,或者先进行乘法运算。

(double) diceData / max * longest
diceData * longest / max

如果使用第二种方法,请注意溢出。