Question

I've got an excercise from university which looks like:

int a = 10;
int b = 3;

double c = a / b;

The question is: Which value is c.

Now I would say, c is 3.3. It's casted implicit to double before calculating the result. But the correct answer to this question is according to my records 3.0.

How this can be? Does the compiler really calculate the result first as integer and then in a second step casts it to double?

Or did I understand that incorrectly?

Était-ce utile?

La solution

Does the compiler really calculate the result first as integer and then in a second step casts it to double?

Yes

Autres conseils

Does the compiler really calculate the result first as integer and then in a second step casts it to double?

Yes,

Runtime first calculates the RHS result and then converts the result to double. Now in your case as RHS contains int / int so the result is in int and you don't get 3.3.

So if RHS contains double / int or int / double, the type promotion occurs and RHS operands are promoted to double before calculating the result and hence you get 3.3

See what is actually happening is :

double c = (double)    a / b; //double of 3 = 3.0

you have to do

double c = a/(double)b
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top