How do you divide two integers and get a double or float answer in C?
To divide fractions by a whole number, we divide the numerator by the whole number and the denominator stays the same.
The first step to dividing fractions is to find the reciprocal (reverse the numerator and denominator) of the second fraction. Next, multiply the two numerators. Then, multiply the two denominators. Finally, simplify the fractions if needed.
Key idea: Like whole numbers, integers don't include fractions or decimals.
Division of integers means equal grouping or dividing an integer into a specific number of groups. For example, -6 ÷ 2 means dividing -6 into 2 equal parts, which results in -3.
You need to cast one or the other to a float
or double
.
int x = 1; int y = 3; // Before x / y; // (0!) // After ((double)x) / y; // (0.33333...) x / ((double)y); // (0.33333...)
Of course, make sure that you are store the result of the division in a double
or float
! It doesn't do you any good if you store the result in another int
.
Regarding @Chad's comment ("[tailsPerField setIntValue:tailsPer]
"):
Don't pass a double or float to setIntValue
when you have setDoubleValue
, etc. available. That's probably the same issue as I mentioned in the comment, where you aren't using an explicit cast, and you're getting an invalid value because a double is being read as an int.
For example, on my system, the file:
#include <stdio.h> int main() { double x = 3.14; printf("%d", x); return 0; }
outputs:
1374389535
because the double was attempted to be read as an int.
Use type-casting. For example,
main() { float a; int b = 2, c = 3; a = (float) b / (float) c; // This is type-casting printf("%f", a); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With