Home > Software engineering >  Why do I get int value after typecasting but decimal value is in bracket?
Why do I get int value after typecasting but decimal value is in bracket?

Time:09-10

I'm very familiar with c but Today I notice something,

float a=(float)5/2; //this gives 2.5, its okay
float b=(float)(5/2); //this gives 2, why?

Please can you name this topic and any answer will help me.

CodePudding user response:

In this expression in parentheses (5/2) there is used the integer arithmetic. The result of the expression is 2.

In this expression (float)5/2 there is used the floating arithmetic because one of the operands has the type float after its explicit casting (float)5.. The unary casting operator has a higher priority than the division operator /.

You could write equivalently

5.f/2

CodePudding user response:

This is an issue with operator precedence. When you write

(float)5/2

it’s interpreted as

((float) 5) / 2

which means “treat 5 as a float, then divide it by the integer 2.” Therefore, the division is done as floating-point division.

When you write

(float)(5/2)

you’re saying “divide the integer 5 by the integer 2, then treat that as a float.” The division done is therefore integer division, which rounds down, so you get 2 as your result.

  • Related