在 Rust 中将浮点数转换为整数 [英] Convert float to integer in Rust

查看:110
本文介绍了在 Rust 中将浮点数转换为整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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.

推荐答案

尤其是将数字四舍五入的第 2 行.

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, ceilfloor.您可以使用其中一种方法来精确控制发生的情况,而不是依赖于演员表.从 Rust 书中我们可以了解到:

从浮点数转换为整数会将浮点数四舍五入到零.

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

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

This behavior is equivalent to trunc, but if the behavior does matter to you, you should use trunc to ...

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

这篇关于在 Rust 中将浮点数转换为整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆