gpt4 book ai didi

c++ - 这两种类型转换有何不同?

转载 作者:行者123 更新时间:2023-11-30 02:21:16 25 4
gpt4 key购买 nike

我正在 Coursera 上做 MOOC,但这段代码不起作用:

unsigned int W, H, D;     
uint64_t total_weight = 0;
for (unsigned int i = 0; i < N; ++i) {
cin >> W >> H >> D;
total_weight += static_cast<uint64_t>(W * H * D);
}
total_weight *= R;
cout << total_weight;

但是,这个确实:

unsigned int W, H, D;     
uint64_t total_weight = 0;
for (unsigned int i = 0; i < N; ++i) {
cin >> W >> H >> D;
total_weight += static_cast<uint64_t>(W) * H * D;
}
total_weight *= R;
cout << total_weight;

如您所见,区别在于这一行:

total_weight += static_cast<uint64_t>(W) * H * D;

这个类型转换和

有什么不同
total_weight += static_cast<uint64_t>(W * H * D);

?

最佳答案

total_weight += static_cast<uint64_t>(W * H * D);

在这里W * H * D计算为 unsigned int 的乘积s 然后转换为 uint64_t这并不能使您免于 W * H * D 时的潜在溢出计算得出。

total_weight += static_cast<uint64_t>(W) * H * D;

在这里static_cast<uint64_t>(W) * H * D计算为 uint64_t 的乘积作为W被转换到 uint64_tH , D晋升为uint64_t以及。因此,在这种情况下,乘法期间发生溢出的可能性较小。


相关转换规则说明如下:

8 Expressions [expr]

11 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:

...

11.5.2 Otherwise, if both operands have signed integer types or both have unsigned integer types, the operand with the type of lesser integer conversion rank shall be converted to the type of the operand with greater rank.

和:

7.15 Integer conversion rank [conv.rank]

1 Every integer type has an integer conversion rank defined as follows:

...

1.3 The rank of long long int shall be greater than the rank of long int, which shall be greater than the rank of int, which shall be greater than the rank of short int, which shall be greater than the rank of signed char.

1.4 The rank of any unsigned integer type shall equal the rank of the corresponding signed integer type.

关于c++ - 这两种类型转换有何不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48599235/

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