#Conversion between double and int

11 messages · Page 1 of 1 (latest)

lone rampart
#

I was trying to solve a simple question for my homework as below.

// variable dm represents deciemeter and has been initialized earlier in //the code, e.g as
//int dm = 1;

// Correct the formula down below so it will pass all test cases
double meter =  dm/10;
System.out.print( meter );

At first, I thought nothing was wrong and hit "check answer", which returned value 0, the expected value was 0.1. After some testing I concluded that the correct way was to declare meter as java double meter = (double) dm/10
But why is this the correct way? Is it because dm was declared as an int, so 0.1/10 is calculated by the computer, assuming that the answer should be an integer? If this is the case, why doesn't the computer already figure it out when I declared meter as a double?

stone lavaBOT
#

This post has been reserved for your question.

Hey @lone rampart! Please use /close or the Close Post button above when your problem is solved. Please remember to follow the help guidelines. This post will be automatically closed after 300 minutes of inactivity.

TIP: Narrow down your issue to simple and precise questions to maximize the chance that others will reply in here.

plain tide
#

The incorrect example was doing 1/10, which is strictly integer division, and any decimal places are just truncated.

#

Java (and most languages) allow you to assign a double variable to an integer expression, and it'll implicitly convert it. That's why the compiler doesn't automatically change the expression to a double calculation

lone rampart
#

So if I understand you correctly, the compiler evaluates each term and deduces the type, by comparing the involved types e.g dm/10 should have an integer answer since dm and 10 are integers, but double r = 1.0 and r/10 should have a double answer since r is a double and 10 is an integer

plain tide
#

Yes

#

Essentially, the resultant type of a whole mathematical expression is just a result of the types that make it up

lone rampart
#

Ahh, now I understand!

#

Thank you so much Andrew for taking your time and explaining everything in depth : )

stone lavaBOT