两种类型转换有何不同?

How are the two typecasts different?

本文关键字:何不同 类型转换 两种      更新时间:2023-10-16

我正在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 ints 的乘法,然后转换为uint64_t这不会在计算W * H * D时使您免于潜在的溢出。

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

这里static_cast<uint64_t>(W) * H * D计算为uint64_ts的乘法,因为W被转换为uint64_tHD提升为uint64_t。因此,在这种情况下,在乘法过程中遭受溢出的机会较小。


相关转换规则说明如下:

8 表达式 [表达式]

11 许多期望算术操作数或运算数的二元运算符 枚举类型导致转换和产生结果类型类似 道路。目的是产生一个通用类型,这也是 结果。这种模式称为通常的算术转换, 定义如下:

11.5.2 否则,如果两个操作数都有有符号整数类型或都有无符号整数类型,则类型较小的操作数 整数转换秩应转换为操作数的类型 具有更高的等级。

和:

7.15 整数转换排名 [转换排名]

1 每个整数类型都有一个整数转换排名,定义为 遵循:

1.3 长长国际的等级应大于长整的等级,长国际的等级应大于国际的等级,国际的等级应为 大于短 int 的秩,该等级应大于 已签名字符的等级。

1.4 任何无符号整数类型的秩应等于相应有符号整数类型的秩。