4

Here is part of my code. The rest is just the function definitions. I have an array of 20 x 20 that records the temperature of a plate. I need to reiterate through a loop until no cell in the array changes more than 0.1 degree (I refresh the values through every iteration) How would you monitor the largest change for any cell in an array in order to determine when to stop iterating? Right now I have tried this, but it doesn't output correctly. I believe it is because I am incorrectly defining my previous one to compare the current one with.

while (true)
{
    bool update = false;
    for (int a = 1; a < array_size -1; a++)
    {
        for (int b = 1; b < array_size -1; b++)
        {             
            hot_plate[a][b] = sum_cell(hot_plate, a, b);

        }
    } 

    for (int a = 1; a < array_size-1; a++)
    {
        for (int b = 1; b < array_size-1; b++)
        {
            hot_plate_next[a][b]=sum_cell(hot_plate_next, a,b);
            if (abs(hot_plate_next[a][b] - hot_plate[a][b]) > 0.1)
            {
                update = true;
            }
            hot_plate_next[a][b] = hot_plate[a][b];
            cout << hot_plate[a][b] << " ";
        }  
    }

    if (!update) {
        break;
    }
}
4

2 回答 2

1

问题是update当单元格的变化较小时您会覆盖。在这种情况下,任何变化较小的单元格都将停止迭代。

像这样构造你的循环:

float largest_change = 0.0f;
do {
    largest_change = 0.0f;

    for (...) {
        float new_value = ...
        float change = abs(new_value - hot_plate[a][b]);
        if (change > largest_change)
            largest_change = change;
        hot_plate[a][b] = change;
    }
} while (largestChange > 0.1f);
于 2012-10-18T15:01:47.843 回答
1

When you put:

        if (abs(hot_plate_next[a][b] - hot_plate[a][b]) < 0.1)
        {
            update = false;
        }

inside the 2nd nested for-loop, you are setting "update" to false if ANY of the cells have a difference less than 0.1 between current and previous checks, instead of ALL cells like you wanted.

Update your code as follows:

    bool update = false;

and

    if (abs(hot_plate_next[a][b] - hot_plate[a][b]) > 0.1)
    {
        update = true;
    }

(I would have put >=, but you said "until no cell in the array changes more than 0.1 degree")

Edit as per request: to output the matrix cleanly, add the following line:

 cout << "\n";

here:

for (int a = 1; a < array_size-1; a++)
{
    for (int b = 1; b < array_size-1; b++)
    {
        hot_plate_next[a][b]=sum_cell(hot_plate_next, a,b);
        if (abs(hot_plate_next[a][b] - hot_plate[a][b]) > 0.1)
        {
            update = true;
        }
        hot_plate_next[a][b] = hot_plate[a][b];
        cout << hot_plate[a][b] << " ";
    }  
    cout << "\n"; // Add this line
}
于 2012-10-18T14:58:39.850 回答