double b = a / 100000;
b = (int) b;
b *= 100000;
如何将上述 C 代码转换为 Rust?特别是将数字四舍五入的第 2 行。
最佳答案
Especially the line #2 that rounds the number.
首先:这不是真的。 “四舍五入”一个实数就是返回最接近的整数。您只需将其转换为 int
即可丢弃所有非整数部分。
但这里是你的确切代码的 Rust 等价物(假设 a
的类型为 f64
):
let b = a / 100_000.0; // underscore in number to increase readability
let b = b as i64;
let b = b * 100_000;
当然也可以写成一行:
let b = ((a / 100_000.0) as i64) * 100_000;
如果你想四舍五入而不是只取整数部分,你可以使用 round
f64
的方法:
let b = ((a / 100_000.0).round() as i64) * 100_000;
注意还有trunc
, ceil
和 floor
.您可以使用其中一种方法来精确控制发生的事情,而不是依赖类型转换。 From the Rust book我们可以学习:
Casting from a float to an integer will round the float towards zero.
此行为等同于 trunc
,但如果该行为对您来说很重要,您应该使用 trunc
来...
- ...用代码表达你的意图
- ...即使 Rust 编译器改变了转换语义也有有效的语义
关于rust - 在 Rust 中将 float 转换为整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37506672/