不同的数据类型操作双浮动

时间:2021-05-11 16:26:07

I know that when having to do with operators in Java , and different data types, then the result is promoting to the larger of the data types So, because double is larger than float, when having for example

我知道当与Java中的运算符和不同的数据类型有关时,结果是提升到更大的数据类型所以,因为double大于float,当有例如

double z=39.21;
float w=2.1F;
System.out.println(z+w );

The result z+w will be of double type. If I don't put the F on the float data type, then the float is assumed to be double.

结果z + w将是双重类型。如果我没有将F放在浮点数据类型上,则假定浮点数为double。

So why the below code does not compile??

那么为什么下面的代码不能编译?

double z=39.21;
float w=2.1;
System.out.println(z+w );

Shouldn't the result just be double, if both z and w are considered double??? Instead it throws:

如果z和w都被认为是双重的话,结果不应该是双倍的吗?而是抛出:

Arithmetic.java:26: error: incompatible types: possible lossy conversion from double to float 
float w=2.1; 
        ^ 
1 error

Also, when

short x = 14;
float y = 13;
double z = 30;
System.out.println( x * y / z);

First, the short gets converted to int. Then the int gets converted to Float. Then multiplication happens.

首先,short被转换为int。然后int转换为Float。然后乘法发生。

Why does in this case compile , since we have an operation between a double and a float without an F??????

为什么在这种情况下编译,因为我们在double和float之间有一个操作而没有F ??????

I cannot seem to understand that case can you help me?

我似乎无法理解你可以帮助我吗?

1 个解决方案

#1


1  

float w = 2.1;  // error

By default, 2.1 is a Double literal.

默认情况下,2.1是双字面值。

Compiler wants an assurance from your side that you're ready to perform the narrowing conversion, that's why it expects a F (or f) after the literal.

编译器希望你方保证你已经准备好执行缩小转换,这就是为什么它希望在文字之后得到F(或f)。

If you don't put an F(OR f), it will result in compilation error.

如果未放置F(或者f),则会导致编译错误。

float y = 13;   // works successfully.

Whereas, in the other case, 13 is an Integer literal. So, it easily gets into a float type. Therefore, the code works successfully.

而在另一种情况下,13是Integer字面值。因此,它很容易进入浮动类型。因此,代码成功运行。

#1


1  

float w = 2.1;  // error

By default, 2.1 is a Double literal.

默认情况下,2.1是双字面值。

Compiler wants an assurance from your side that you're ready to perform the narrowing conversion, that's why it expects a F (or f) after the literal.

编译器希望你方保证你已经准备好执行缩小转换,这就是为什么它希望在文字之后得到F(或f)。

If you don't put an F(OR f), it will result in compilation error.

如果未放置F(或者f),则会导致编译错误。

float y = 13;   // works successfully.

Whereas, in the other case, 13 is an Integer literal. So, it easily gets into a float type. Therefore, the code works successfully.

而在另一种情况下,13是Integer字面值。因此,它很容易进入浮动类型。因此,代码成功运行。