rust - 在 Rust 中将 float 转换为整数

标签 rust

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 , ceilfloor .您可以使用其中一种方法来精确控制发生的事情,而不是依赖类型转换。 From the Rust book我们可以学习:

Casting from a float to an integer will round the float towards zero.

此行为等同于 trunc,但如果该行为对您来说很重要,您应该使用 trunc 来...

  1. ...用代码表达你的意图
  2. ...即使 Rust 编译器改变了转换语义也有有效的语义

关于rust - 在 Rust 中将 float 转换为整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37506672/

相关文章:

rust - 将 Ref 的内容与 PartialEq 进行比较

rust - 如何将数据移动到多个 Rust 闭包中?

c++ - Rust 中的侵入式算法等价物

struct - Rust 在嵌入另一个结构的结构上使用高阶函数

struct - 没有从在Rust中实现特征的结构推断出的特征吗?

rust - 使用 * 和 & 比较值是否相等有什么区别?

Rust 构建脚本将文件复制到目标目录

methods - 翘曲的根路径示例?

rust - 我可以将函数标记为已弃用吗?

parsing - 当输入为 &str 时,如何获取多个顺序 nom 解析器的输出?