Why do I get int value after typecasting but decimal value is in bracket?

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.

Upvotes: 0

Views: 85

Answers (2)

templatetypedef
templatetypedef

Reputation: 373382

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.

Upvotes: 2

Vlad from Moscow
Vlad from Moscow

Reputation: 311126

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

Upvotes: 2

Related Questions