Integer division: How do you produce a double?

2018-12-31 00:43发布

For this code block:

int num = 5;
int denom = 7;
double d = num / denom;

the value of d is 0.0. It can be forced to work by casting:

double d = ((double) num) / denom;

But is there another way to get the correct double result? I don't like casting primitives, who knows what may happen.

10条回答
心情的温度
2楼-- · 2018-12-31 01:13
double num = 5;

That avoids a cast. But you'll find that the cast conversions are well-defined. You don't have to guess, just check the JLS. int to double is a widening conversion. From §5.1.2:

Widening primitive conversions do not lose information about the overall magnitude of a numeric value.

[...]

Conversion of an int or a long value to float, or of a long value to double, may result in loss of precision-that is, the result may lose some of the least significant bits of the value. In this case, the resulting floating-point value will be a correctly rounded version of the integer value, using IEEE 754 round-to-nearest mode (§4.2.4).

5 can be expressed exactly as a double.

查看更多
旧人旧事旧时光
3楼-- · 2018-12-31 01:16

If you change the type of one the variables you have to remember to sneak in a double again if your formula changes, because if this variable stops being part of the calculation the result is messed up. I make a habit of casting within the calculation, and add a comment next to it.

double d = 5 / (double) 20; //cast to double, to do floating point calculations

Note that casting the result won't do it

double d = (double)(5 / 20); //produces 0.0
查看更多
残风、尘缘若梦
4楼-- · 2018-12-31 01:16

Best way to do this is

int i = 3;
Double d = i * 1.0;

d is 3.0 now.
查看更多
栀子花@的思念
5楼-- · 2018-12-31 01:17

I don't like casting primitives, who knows what may happen.

Why do you have an irrational fear of casting primitives? Nothing bad will happen when you cast an int to a double. If you're just not sure of how it works, look it up in the Java Language Specification. Casting an int to double is a widening primitive conversion.

You can get rid of the extra pair of parentheses by casting the denominator instead of the numerator:

double d = num / (double) denom;
查看更多
余欢
6楼-- · 2018-12-31 01:17

Cast one of the integers/both of the integer to float to force the operation to be done with floating point Math. Otherwise integer Math is always preferred. So:

1. double d = (double)5 / 20;
2. double v = (double)5 / (double) 20;
3. double v = 5 / (double) 20;

Note that casting the result won't do it. Because first division is done as per precedence rule.

double d = (double)(5 / 20); //produces 0.0

I do not think there is any problem with casting as such you are thinking about.

查看更多
情到深处是孤独
7楼-- · 2018-12-31 01:17

just use this.

int fxd=1;
double percent= (double)(fxd*40)/100;
查看更多
登录 后发表回答