Unexpected result in long/int division

2019-01-09 12:23发布

问题:

I have values like this:

long millis = 11400000;
int consta = 86400000;
double res = millis/consta;

The question is: why res equals 0.0 (instead of ca. 0.131944)? It's stored in double so there should be no rounding right?

回答1:

When you are using a binary operator, both arguments should be of a same type and the result will be in their type too. When you want to divide (int)/(long) it turns into (long)/(long) and the result is (long). you shouldmake it (double)/(long) or (int)/(double) to get a double result. Since double is greater that int and long, int and long will be turned into double in (double)/(long) and (int)/(double)



回答2:

Because you are dividing a long by an int you get an long results. What you are effectively doing is

double res = (double) (millis/consta);

as millis/consta is 0, when cast to double is 0.0

Try the following to divide a double by an int and get a double result.

double res = (double) millis/consta;

which is the same as

double res = ((double) millis)/((double) consta));


回答3:

You are doing longdivision (int gets cast to long) so you get long values, which are integers (so, 0)

You should do

  double res = (double) millis / consta;

Once one of the values is casted to double, the other is too casted so the operation uses the same type in both operators.



回答4:

millis/consta is an integer division, which results in 0. the casting in the line:

double res = millis/consta;

is done on the result:

double res = (double)(millis/consta);

What you need to do is to cast one of the operands:

double res = (double)millis/consta;


回答5:

The resulting type of a long and int devision will be a long, which can't hold decimals.

you want to cast it to a double before you assign it



回答6:

When this happens it automatically downcasts to int to perform the operation. Thy writing it like:

long millis = 11400000;
int consta = 86400000;
double res = ((double)millis)/((double)consta);

And it will work.



回答7:

This is because long: The long data type is a 64-bit signed two's complement integer. int: The int data type is a 32-bit signed two's complement integer.

See Primitive type It means both are integer. Since we divide long by integer, result is long 0. But you assign this value to res(double) value and print it. So the result 0.0 is shown.

long millis = 11400000;
int consta = 86400000;

System.out.println("millis/consta = " + millis/consta); // print 0

double res = millis/consta;
System.out.println("Res " + res); // print 0.0