gpt4 book ai didi

java - (float)m/f 和 (float)(m/f) 的区别

转载 作者:太空狗 更新时间:2023-10-29 23:51:17 25 4
gpt4 key购买 nike

int m = 10;
int f = 3;
float r = (float)m/f; // gives 3.333333 as output
float r = (float)(m/f); // gives 3.0 as output

谁能告诉我括号是如何改变答案的,因为我基本上是将 m/f 的整数值类型转换为 float 。我不明白的是,在 m/f 周围添加方括号是如何改变答案的。

最佳答案

第二种情况:

(float)(m/f)

您首先进行整数除法,然后转换为 float ,因此您丢失了分数。在第一种情况下,您将 m 转换为 float,因此最终执行浮点除法。

cast 运算符有 higher precedence在 C++ 和 Java 中,但在除法两边使用括号会强制首先对其求值。

C++ 中,他的行为是由于 通常的算术转换 引起的,这在草案 C++ 标准部分 5 表达式 10 段说:

Many binary operators that expect operands of arithmetic or enumeration type cause conversions and yield result types in a similar way. The purpose is to yield a common type, which is also the type of the result. This pattern is called the usual arithmetic conversions, which are defined as follows:

并包括以下项目符号:

— Otherwise, if either operand is float, the other shall be converted to float.

Java 中,此行为包含在 JLS section 5.6.2. Binary Numeric Promotion 中其中说:

When an operator applies binary numeric promotion to a pair of operands, each of which must denote a value that is convertible to a numeric type, the following rules apply, in order:

并包括:

Widening primitive conversion (§5.1.2) is applied to convert either or both operands as specified by the following rules:

并包括:

Otherwise, if either operand is of type float, the other is converted to float.

并包括以下示例:

int i    = 0;
float f = 1.0f;

// First int*float is promoted to float*float, then

关于java - (float)m/f 和 (float)(m/f) 的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22418979/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com