Beginner Question: Make a function that divides a number by 100

Hi everyone!
I'm super new to Rust. My background is in JavaScript/PHP, so there are many aspects of this wonderful language I'm still learning.

I'm currently trying to understand what I'm doing wrong here. I'm trying to make a function that divides a number by 100. However, I'm running into some type errors. What am I doing wrong?

fn main() {
    let x = divide_by_one_hundred(1749.0);

    println!("The value of x is: {}", x);
}

fn divide_by_one_hundred(x: f32) -> f32 {
    x / 100
}

Rust will not automatically convert between different number types, and this includes conversions between integer and floating point types. To create a floating point, you must include a period. For example:

fn divide_by_one_hundred(x: f32) -> f32 {
    x / 100.0
}
1 Like

Hmm, the compiler is uncharacteristically unhelpful, here. I've opened a bug to improve the diagnostic

https://github.com/rust-lang/rust/issues/93829

10 Likes

That's a bit too strong a word, isn't it? The very first line of the error message says:

cannot divide `f32` by `{integer}`

which is the problem. I'm not saying it shouldn't include a suggestion, but the error itself is already pretty clear.

The error is correct, and it's sufficient for a non-beginner to be able to resolve the problem. It's certainly not misleading.

All I mean by it is that the compiler does such an good job in so many of these basic cases that I was surprised it didn't provide additional help in this one.

For example, this one is not only clear and correct, but also actively helpful:

error[E0308]: mismatched types
 --> src/lib.rs:5:9
  |
5 |     bar(x);
  |         ^ expected `f64`, found `f32`
  |
help: you can convert an `f32` to an `f64`
  |
5 |     bar(x.into());
  |          +++++++

(As a non-beginner I don't need that help, and if you did an eye tracking study it would probably find that I don't normally even read it, since the caret message is sufficient for me to start fixing my code. But I've been conditioned to be surprised when something like it isn't there.)

5 Likes

Don't forget that if the help: section is tagged as MachineApplicable, then the rust-analyzer IDE plugins will have a one-click fix, so they're still worth writing for experienced programmers too.

5 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.