简体   繁体   中英

objective c float values

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 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.

int a = 100;
int b =50;
float temp = (float)b/a;

Its integer division - 50/100 is 0, the remainder (can use modulus) is 50.

You will need to use floats, whether you cast from int or start with them is up to you.

The below statement means, you are casting your integer values into float before staring the operation

float temp = (float)b / (float)a;

So could be seen as below

float temp = (float)50 / (float)100;

then

float temp = 50.0 / 100.0 ;

And result

temp = 0.5;

In your case 50/100 is 0.2. By obtaining the result for two integer numbers the result will also be in integer form so it truncates the decimal part giving you 0 alone. But in case of float it is considered as a floating division so you will get 0.2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM