Why we can not store the division result of two integers into the float variable ?
int a = 100;
int b =50;
float temp = b/a;
it gives t= 0 !
also i did
int temp = b/a;
it gives t= 0 !
but when I did
float temp = (float)b / (float)a;
it gives proper result. Why so ?
The reason why
float temp = b/a;gives 0 whilefloat temp = (float)b/a;gives 0.5 is that the compiler determines the output type of the division operation based upon the types of the operands, not the destination storage type. Put simply:So when you do
float temp = b/a;you’re doing in integer divide ofbanda, and then storing the resulting integer (0 in your example) into a variable of typefloat. In essence, by the time the value is converted to floating-point you have already lost the information you are looking for (assuming you wanted to do a floating-point divide), and the conversion is not going to bring it back.In order to get the result you want (again, assuming that you want to do a floating-point divide), you need to cast at least one of the operands to
floatbefore you divide.