Ryan Gibson
Ryan Gibson

Reputation: 283

Possible Overflow C

I have several variables listed below:

int cpu_time_b  = 6
float clock_cycles_a = 2 * pow(10, 10));
float cpi_a = 2.0;
int cycle_time_a = 250;
float cpi_b = 1.2;
int cycle_time_b = 500 

I am working out the clock rate of b with the following calculation:

(((1.2*clock_cycles_a)/cpu_time_b)/(1 * pow(10, 9)))

Clearly the answer should be 4 however my program is outputting 6000000204800000000.0 as the answer

I think that overflow is possibly happening here. Is this the case and if so, how could I fix the problem?

Upvotes: 0

Views: 115

Answers (1)

Sebastien
Sebastien

Reputation: 1476

All calculations should be made to ensure comparable numbers are "reduced" together. in your example, it seems like only

cpu_time_b

is truly variable (undefined in the scope of your snippet. All other variables appears as constants. All constants should be computed before compilation especially if they are susceptible to cause overflow.

clock_cycles_a

cancels the denominator. pow is time consuming (may not be critical here) and not always that precise. You multiply the 2 explicitly when you declare clock_cycles_a and then use 1.2 below. etc. Reducing the whole thing keeping only the actual variable becomes:

24.0/cpu_time_b

which makes me deduce that cpu_time_b should be 6?

Finaly, while you write the equation, we have no idea of what you do with the result. Store it in the wrong variable type? printf with the wrong format? etc?

Upvotes: 1

Related Questions