java - Unexpected result while dividing int by int and storing result into double -


this question has answer here:

i'm having weird problem.

this code divides int int, stores result in double variable , prints it:

int = 200; int b = 557;  double divisionresult = / b;  system.out.println("result: " + divisionresult); 

after executing code, output is:

result: 0 

this weird, because 200/557 0.3590664272890485

i noticed if cast a , b double in division line

double divisionresult = (double) / (double) b; 

it works perfectly.

why have cast variables double real division result?

because in integer division, if answer not perfect integer, digits after decimal point removed (integer division yields integer value).

note don't have cast both integers, can cast one, second implicitly converted.

why after cast works?

because cast has higher precedence /. first cast, divides. if not case, 0.0.


Comments

Popular posts from this blog

linux - Does gcc have any options to add version info in ELF binary file? -

android - send complex objects as post php java -

charts - What graph/dashboard product is facebook using in Dashboard: PUE & WUE -