在 Rust 中有多少种方法可以声明浮点数?

Dig*_*i55 1 variables floating-point rust

我看到了以下可能性:

let first_float: f64 = 3.4;
let second_float = 4.5f64;
let third_float = 5.6 as f64;
Run Code Online (Sandbox Code Playgroud)

还有其他方法可以声明浮点数吗?我不是指不同的浮点类型,如f32和f64。

mca*_*ton 9

当然有。

首先让我们解释一下你的方法是做什么的。它们结合了语言的不同特性,虽然它们似乎都“在 Rust 中声明了一个浮点数”,但它们并不是简单的声明。

// Float literals will become either `f32` or `f64`
// depending on how they're are used:
let first_float: f64 = 3.4;

// This one is really a `f64` literal,
// typically only used when inference isn't enough
let second_float = 4.5f64; 

// This is an identity cast, the untyped literal will give f64 since that
// is what is needed at the end. I would never use this.
let third_float = 5.6 as f64; 
Run Code Online (Sandbox Code Playgroud)

浮动是f64默认的,所以这是你大部分时间应该使用的:

// Float literals will become either `f32` or `f64`
// depending on how they're are used:
let first_float: f64 = 3.4;

// This one is really a `f64` literal,
// typically only used when inference isn't enough
let second_float = 4.5f64; 

// This is an identity cast, the untyped literal will give f64 since that
// is what is needed at the end. I would never use this.
let third_float = 5.6 as f64; 
Run Code Online (Sandbox Code Playgroud)

这里有一些其他过于复杂的方法:

let _another_one = 3.4;
Run Code Online (Sandbox Code Playgroud)