相关疑难解决方法(0)

如何乘法/除/加/减不同类型的数字?

我正在研究Rust手册的第二版,并决定尝试制作经典的Celsius-to-Fahrenheit转换器:

fn c_to_f(c: f32) -> f32 {
    return ( c * ( 9/5 ) ) + 32;
}
Run Code Online (Sandbox Code Playgroud)

编译cargo build它将产生编译时错误:

error[E0277]: the trait bound `f32: std::ops::Mul<{integer}>` is not satisfied
 --> src/main.rs:2:12
  |
2 |     return (c * (9 / 5)) + 32;
  |            ^^^^^^^^^^^^^ the trait `std::ops::Mul<{integer}>` is not implemented for `f32`
  |
  = note: no implementation for `f32 * {integer}`
Run Code Online (Sandbox Code Playgroud)

作为一个新的Rust程序员,我的解释是我不能将float和integer类型相乘.我通过使所有常量浮点数解决了这个问题:

fn c_to_f(c: f32) -> f32 {
    return ( c * ( 9.0/5.0 ) ) + 32.0; …
Run Code Online (Sandbox Code Playgroud)

math arithmetic-expressions rust

10
推荐指数
1
解决办法
3337
查看次数

如何在 Rust 中将有符号整数添加到无符号整数,检查无符号溢出?

我想将 a 添加isize到 ausize并包括边界检查,以便结果不会溢出 a 的边界usize。如何才能做到这一点?

unsigned signed rust

1
推荐指数
1
解决办法
161
查看次数

标签 统计

rust ×2

arithmetic-expressions ×1

math ×1

signed ×1

unsigned ×1