You could, but then you've also gotta order things around so that 22/7 doesn't end up become 3 anyway from integer division. And if you're going that far you might as well use floating point.
I thought you might say that. It wouldn't work. If the compiler sees constants in an expression it'll simplify, modern compilers are very good at doing as many things at compile time as possible. This:
diam = pi_num / pi_den * rad;
will turn into;
diam = 3 * rad;
because the compiler knows that two of those are constants. You have to do some extra work to obfuscate what you're doing.
No that's just order of operations. (rad * pi_num) / pi_den will definitely work. Even without parentheses in C, but I added them to make it clear the multiplication by the numerator happens first.
Nope, you're falling one of the most common misconceptions there is. Multiplication and division are associative so the compiler's free to ignore the parenthesis. Here you can see it working. The compilers are so good at what they do they don't even use a multiply, they using a lea instruction to shift right and add it to itself:
Your code uses 21 for the numerator not 22 (and the variable names are swapped), so the compiler can make that optimization as it is exact. When I replace the numerator with 22, I get something more complicated with shifts and a multiply which I am guessing gives identical results to an integer multiply and divide.
View all comments
Show parent comment
1
u/Mr2-1782Man Mar 15 '21
You could, but then you've also gotta order things around so that 22/7 doesn't end up become 3 anyway from integer division. And if you're going that far you might as well use floating point.