Check out this code from production line for displaying pie charts of expenses. I declare arrays of float totals for each of 3 pie charts.
float totals[NUMPIES];
totals[PIE1] = 0;
totals[PIE24] = 0;
totals[PIEALL] = 0;
Then I declare a 2-dimensional array of floats which I fill with some data. As I build up those amounts I also update the totals:
float amounts[NUM_FINANCE_CATEGORIES][NUMPIES];
for (int r = 0; r < NUM_FINANCE_CATEGORIES; r++)
{
if (r != FC_CAR_SALES)
{
amounts[r][PIE1] = SIM_GetFinanceRecords()->GetAmount(1, (FINANCE_CATEGORY)r);
amounts[r][PIE24] = SIM_GetFinanceRecords()->GetAmount(24, (FINANCE_CATEGORY)r);
amounts[r][PIEALL] = SIM_GetFinanceRecords()->GetAmount(-1, (FINANCE_CATEGORY)r);
totals[PIE1] += amounts[r][PIE1];
totals[PIE24] += amounts[r][PIE24];
totals[PIEALL] += amounts[r][PIEALL];
}
}
Then some simple resetting of data, which is irrelevant for this bug, and a check that I am not about to divide by zero:
Pies[PIE1]->Clear();
Pies[PIE24]->Clear();
Pies[PIEALL]->Clear();
if (totals[PIE1] <= 0 || totals[PIE24] <= 0 || totals[PIEALL] <= 0)
{
return;
}
Then the final code:
//now create
for (int r = 0; r < NUM_FINANCE_CATEGORIES; r++)
{
if (r != FC_CAR_SALES)
{
for (int p = 0; p < NUMPIES; p++)
{
float perc = amounts[r][p] / totals[p];
assert (perc >= 0 && perc <= 1.0f)
Hold ON STOP!. How can that assert ever trigger? EVER? (it does for some people). Its driving me mad :D. It can ONLY trigger if one of the amounts in the array is less than 0% or more than 100% of the total. I KNOW that the total is greater than zero, so the amount must be greater than zero. The total is only comprised of the sum of the amounts. There is no way these numbers can be out of synch, PLUS, they are all floating point vars so there is no rounding going on… or is it maybe a tiny tiny quantizing thing? (I’ve update the game with extra debug data for this error so I’ll find out soon). Surely thats the only explanation, and perc is something like 1.000000001%?