问题描述
double b = a / 100000;
b = (int) b;
b *= 100000;
上面的 C 代码是如何转换为 Rust 的?尤其是将数字四舍五入的第 2 行.
How the above C code is converted to Rust? Especially the line #2 that rounds the number.
推荐答案
首先:这不是真的.舍入"一个实数就是返回最接近的整数.您只需将其转换为 int
即可丢弃所有非整数部分.
First of all: this is not true. To "round" a real number is to return the nearest integer. You just convert it to int
which discards all the non-integer parts.
但这里是您的确切代码的 Rust 等价物(假设 a
具有 f64
类型):
But here is the Rust equivalent of your exact code (assuming a
has the type f64
):
let b = a / 100_000.0; // underscore in number to increase readability
let b = b as i64;
let b = b * 100_000;
当然,也可以写成一行:
Which, of course, can be written in one line, too:
let b = ((a / 100_000.0) as i64) * 100_000;
如果你想四舍五入而不是只取整数部分,你可以使用 round
f64
的方法:
If you wanted to round instead of just taking the integer part, you can use the round
method of f64
:
let b = ((a / 100_000.0).round() as i64) * 100_000;
注意还有trunc
, ceil
和 floor
.您可以使用其中一种方法来精确控制发生的情况,而不是依赖于演员表.从 Rust 书中我们可以了解到:
从浮点数转换为整数会将浮点数四舍五入到零.
此行为等效于 trunc
,但如果该行为对您很重要,则应使用 trunc
来...
This behavior is equivalent to trunc
, but if the behavior does matter to you, you should use trunc
to ...
- ...用代码表达你的意图
- ... 即使 Rust 编译器更改了强制转换语义,也具有有效的语义
这篇关于在 Rust 中将浮点数转换为整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!