Object Values ​​with float

Why can't we save the result of dividing two integers into a float variable?

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

gives t = 0!

and i did

 int temp = b/a; 

gives t = 0!

but when i did

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

he gives the correct result. Why is that?

+7
source share
5 answers

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 .

+22
source
 int a = 100; int b =50; float temp = (float)b/a; 
+3
source

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

You will need to use floats, regardless of whether you drop from int or start with them, it is up to you.

+3
source

The above statement means that you throw integer values ​​in a float before you view the operation

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

So you can see below

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

then

 float temp = 50.0 / 100.0 ; 

And the result

 temp = 0.5; 
+3
source

In your case, 50/100 is 0.2. Having received the result for two integers, the result will also be in integer form, so it truncates the decimal part, giving you only one. But in the case of float it is considered a floating division, so you get 0.2

+2
source

All Articles