I am having trouble getting the right output for one of my functions. I am able to compute the correct average for the first function, but for my second my answer is off by a few numbers.
I really just want to understand what I am doing wrong, and what I can do to fix it.
void MyAverage(double hot_plate[][SIZE])// This is the function I am having trouble computing the right average.
{
const double NEIGHBORS = 4.0;
double average_temp = 0.0;
double largest_change = 0.0;
Seems to me that you're making a program that simulates a hot plate.
First I'd take out the idea of taking the average of the current position into another function
1 2 3 4 5 6 7 8 9 10 11 12
double Average4(double a, double b, double c, double d) {
return (a + b + c + d)/4.0;
}
double NeighborAverage(double hot_plate[SIZE][SIZE], int row, int col) {
return Average4(
hot_plate[row][col - 1],
hot_plate[row + 1][col],
hot_plate[row][col + 1],
hot_plate[row - 1][col]
);
}
Now call this function in those parts where its asking to calculate the average. average = NeighborAverage(hot_plate, row, col);
This should make the actual calculation repeatable and printable. But I think the real error is here. double change = hot_plate[row][col] - old_value;
Knowing that all parts of the plate start at 100 except the edges that start at 0, the new average for each position should be lower than the previous for the first iteration. Meaning you'll get a negative change everywhere. Meaning that change value should be negative.
making this largest_change > CHANGE probably not be what you'd like since change is positive 0.1. You'd probably prefer std::abs(largest_change) > CHANGE as your do-while loop exit condition.
Finally know that floating point numbers are actually not exact. Due to the way the computer calculates floating point numbers it may have a few errors that can be better reasoned about and ignored by printing out the entire value.