简体   繁体   中英

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

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?

As brackets have the highest precedence, they get solved first

float firstValue  = (float) (5 / 2);  // division of integers
                  = (float) (2);      // 5/2 = 2 , as Integers are being divided
                  = 2f
float secondValue = (float) 5 / 2; // division of float with integer
                  = ((float) 5) / 2;
                  = 5f / 2;          // second value is equivalent to this
                  = 2.5f             // as Float divided by Integer is Float
  1. float firstValue = (float) (5 / 2); // division of integers

The first step is to do 5/2 calculation.Then the answer is given in float.If you explain further 5 and 2 are int numbers. After calculating the int for two int numbers, the final answer is returned by int. Here the final int answer (2) is converted to a float answer. That is, wider conversion is used here. So the final answer is the integer value(2) shown in float form(2.0).

2.float secondValue = (float) 5 / 2; //output is 2.5 Since the first value(5) is named a float number, the final answer is the decimal itself

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 .

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