The reason float temp = b/a; gives 0, and float temp = (float)b/a; gives 0.5, is that the compiler determines the output type of the division operation based on the types of operands, and not the type of the target storage. Simply put:
int / int = int float / int = float int / float = float float / float = float
So, when you do float temp = b/a; , you split the integers b and a , and then save the resulting integer (0 in your example) into a variable of type float . In fact, by the time you convert the value to a floating point, you have already lost the information you are looking for (provided that you want to do floating point separation), and the conversion will not return it.
In order to get the desired result (again, assuming that you want to do floating-point separation), before you split, you need to drop at least one of the operands to float .
aroth
source share