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 ?
@property (nonatomic) float rating; @property (nonatomic) float mRating; Asterisks indicate pointers. All Objective C classes are declared with asterisks, because instances are referred to through pointers.
Definition and Usage The float keyword is a data type that can store fractional numbers from 3.4e−038 to 3.4e+038.
The reason why float temp = b/a;
gives 0 while float 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:
int / int = int
float / int = float
int / float = float
float / float = float
So when you do float temp = b/a;
you're doing in integer divide of b
and a
, and then storing the resulting integer (0 in your example) into a variable of type float
. 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 float
before you divide.
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