【问题标题】:How do I multiply an integer and a floating value together and display the result as a floating value in Rust? [duplicate]如何将整数和浮点值相乘并将结果显示为 Rust 中的浮点值? [复制]
【发布时间】:2018-07-16 00:05:16
【问题描述】:

我有以下代码:

struct Stuff {
    thing: i8
}

fn main(){
    let theStuff = Stuff { thing: 1 };
    println!("{}", theStuff.thing * 1.5);
}

我在编译时得到以下信息:

error[E0277]: the trait bound `i8: std::ops::Mul<{float}>` is not satisfied
 --> IntFloatMultiply.rs:7:32
  |
7 |  println!("{}", theStuff.thing * 1.5);
  |                                ^ no implementation for `i8 * {float}`
  |
  = help: the trait `std::ops::Mul<{float}>` is not implemented for `i8`

我读过一些其他的帖子,包括一堆让我很头疼的东西(包括https://stackoverflow.com/a/44552464/1678392)。如果我没有具体的答案,我不在乎技术细节、什么或为什么。如何编译此代码以显示浮点结果?

【问题讨论】:

    标签: rust


    【解决方案1】:

    假设您希望 1 * 1.5 的结果为浮点数,您可以使用 as 运算符将 thing 转换为 f64

    fn main() {
        let the_stuff = Stuff { thing: 1 };
        println!("{}", the_stuff.thing as f64 * 1.5);
    }
    

    这打印出1.5。 Rust 迫使您明确说明不同数字类型的交互方式。

    假设您总是将i8 乘以1.5,那么您可以将结果放入f32 返回类型中:

    fn main() {
        let the_stuff = Stuff { thing: i8::max_value() };
        println!("{}", the_stuff.thing as f32 * 1.5);
    }
    

    【讨论】:

      猜你喜欢
      • 2021-07-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-27
      • 1970-01-01
      相关资源
      最近更新 更多