14.2.6.2 Binary numeric promotions

博客介绍了预定义二元运算符的二进制数值提升规则,它会将操作数隐式转换为共同类型。规则按顺序包括不同类型操作数的转换,如decimal、double、float等。还指出不允许decimal与double、float混合运算,可通过强制类型转换解决不兼容问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

This clause is informative.
Binary numeric promotion occurs for the operands of the predefined +, ?, *,
/, %, &, |, ^, ==, !=, >, <, >=,
and <= binary operators. Binary numeric promotion implicitly converts both
operands to a common type
which, in case of the non-relational operators, also becomes the result
type of the operation. Binary numeric
promotion consists of applying the following rules, in the order they
appear here:
?If either operand is of type decimal, the other operand is converted to
type decimal, or a compiletime
error occurs if the other operand is of type float or double.
?Otherwise, if either operand is of type double, the other operand is
converted to type double.
?Otherwise, if either operand is of type float, the other operand is
converted to type float.
?Otherwise, if either operand is of type ulong, the other operand is
converted to type ulong, or a
compile-time error occurs if the other operand is of type sbyte, short,
int, or long.
?Otherwise, if either operand is of type long, the other operand is
converted to type long.
?Otherwise, if either operand is of type uint and the other operand is of
type sbyte, short, or int,
both operands are converted to type long.
?Otherwise, if either operand is of type uint, the other operand is
converted to type uint.
?Otherwise, both operands are converted to type int.
[Note: The first rule disallows any operations that mix the decimal type
with the double and float types.
The rule follows from the fact that there are no implicit conversions
between the decimal type and the
double and float types. end note]
[Note: Also note that it is not possible for an operand to be of type ulong
when the other operand is of a
signed integral type. The reason is that no integral type exists that can
represent the full range of ulong as
well as the signed integral types. end note]
In both of the above cases, a cast expression can be used to explicitly
convert one operand to a type that is
compatible with the other operand.
[Example: In the example
decimal AddPercent(decimal x, double percent) {
return x * (1.0 + percent / 100.0);
}
a compile-time error occurs because a decimal cannot be multiplied by a
double. The error is resolved by
explicitly converting the second operand to decimal, as follows:
decimal AddPercent(decimal x, double percent) {
return x * (decimal)(1.0 + percent / 100.0);
}
end example]
End of informative text.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值