Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

objective c float values

Tags:

c

objective-c

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 ?

like image 207
Maulik Avatar asked Apr 08 '11 10:04

Maulik


People also ask

How to declare float in Objective C?

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

What does float mean in java?

Definition and Usage The float keyword is a data type that can store fractional numbers from 3.4e−038 to 3.4e+038.


1 Answers

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.

like image 181
aroth Avatar answered Oct 02 '22 15:10

aroth