对于循环函数参数错误

时间:2015-12-06 15:11:03

标签: c++ function for-loop

    void Image::setValues(int start_row, int end_row, int start_column, int end_column, Image & source)
{
    int startPosX = start_row;
    int startPosY = start_column;

    for (int row = 0; startPosX < end_row; row++, startPosX++)
        for (int col = 0; startPosY < end_column; col++, startPosY++)
            std::cout << startPosX << "  " << startPosY << std::endl;
}

我将此功能称为

imageTest.setValues(0, 32, 0, 32, imageTest2);

我希望输出1024组数字(32 * 32)而不是输出如下所示。

Output

我做错了什么?

2 个答案:

答案 0 :(得分:1)

您忘记在内循环开始时初始化startPosY

试试这个:

void Image::setValues(int start_row, int end_row, int start_column, int end_column, Image & source)
{
    int startPosX = start_row;
    int startPosY = start_column;

   for (int row = 0; startPosX < end_row; row++, startPosX++) {
        startPosY = start_column;
        for (int col = 0; startPosY < end_column; col++, startPosY++)
            std::cout << startPosX << "  " << startPosY << std::endl;
    }
}

答案 1 :(得分:1)

除了使逻辑变得更复杂并导致你犯错误之外,

startPosXstartPosY没有做任何有用的事情。

没有它们会更简单,更清晰:

for (int row = start_row; row < end_row; row++)
    for (int col = start_column; col < end_column; col++)
        std::cout << row << "  " << col << std::endl;