Why does my float type-casting expression return two different values?

timmyen :

Here are the expressions I'm working with:

float firstValue = (float) (5 / 2); //output is 2.0
float secondValue = (float) 5 / 2; //output is 2.5

I'm stumped here and can't figure out why this type casting is returning two different values. I understand I can just do (5f / 2f) but I wanted to experiment using the other type casting with an expression. Why is firstValue 2.0 and secondValue 2.5? Where did the .5 go?

Elliott Frisch :

The first is integer math. This

float firstValue = (float) (5 / 2); 

First divides five by two and gets two. Then it converts two to 2.0. The second is floating point math.

float secondValue = 5f / 2; 

Which is 2.5 (and a float). Because a float divided by an int is a float.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=219226&siteId=1