在 Java 中将整数乘以浮点数/双精度数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31352273/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 10:57:04  来源:igfitidea点击:

Multiplying by an Integer by a Float/Double in Java

java

提问by alwaysboots

I'm trying to do something so simple: multiply an integer by a float/double:

我正在尝试做一些如此简单的事情:将整数乘以浮点数/双精度数:

public class A {
    public static void main(String[] args) {
        int x =  (int) 0.5 * 100;       
        System.out.println(x);
    }
}

However, although you'd expect this to return x = 50, instead x = 0! The same thing happens when I use float d = 0.5f. Does anyone know what is going on and why this isn't working?

但是,尽管您希望它返回x = 50,但x = 0! 当我使用float d = 0.5f. 有谁知道发生了什么以及为什么这不起作用?

回答by hagrawal

JLS §4.2.4. Floating-Point Operationstell rules governing floating point operation, so as per that if any of the operand is a floating point number than other operand will be widened to a floating point (if not already) and final result will be a floating point number.

JLS §4.2.4。浮点运算告诉控制浮点运算的规则,因此如果任何操作数是浮点数,那么其他操作数将被扩展为浮点数(如果还没有),最终结果将是浮点数。

So, your int100will be widened to 100.0before arithmetic operation, and your result of operation will be 50.0.

因此,您int100将扩大到100.0算术运算之前,并且您的运算结果将是50.0

Now, since you are casting your result to in int, so JSL §5.1.3. Narrowing Primitive Conversionwill be applicable, and double 50.0will be narrowed to int 50.

现在,由于您将结果转换为 in int,因此JSL §5.1.3。Narrowing Primitive Conversion将适用,double50.0将缩小为 int 50

100 is an impossible result, given the code you have provided.

鉴于您提供的代码,100 是不可能的结果。

My guess is that when you got 100, you would have done something else.

我的猜测是,当你得到 100 时,你会做其他事情。

enter image description here

在此处输入图片说明

回答by xpz

int x =  (int) 0.5 * 100; 

it first casts 0.5 to an int ---> 0 then multiplies.

它首先将 0.5 转换为 int ---> 0 然后相乘。