linux - Infinite loop when simplifying fractions in binary in C -
i'm trying simplify fractions in binary code checks if value even:
int is_even(floatlet value){ if(value & 1) return 0; return 1; } and while loop keeps bit shifting until value odd.
while(is_even(numerator) && is_even(denomexp)){ numerator >>= 1; denomexp <<= 1; } the while loop goes on infinite loop. i'm wondering why? we've done test , is_even function works fine. thanks!
your loop incorrect: should shifting demonexp right too. runs indefinitely numerator=0 , denomexp.
if numerator , denomexp integer types, , number fraction numerator/denomexp, can fix code way:
while (numerator && is_even(numerator) && is_even(denomexp)) { numerator >>= 1; denomexp >>= 1; } conversely, if denomexp power of 2 divide numerator, should increment instead, , maybe test overflow:
while (numerator && is_even(numerator)) { numerator >>= 1; denomexp += 1; } you must post type definition , semantics complete code in question.
Comments
Post a Comment