0

My rust calculation code is giving me wrong result, but when I do the same in python or C/C++ it gives me correct result, here is the code -

In rust -

let mem_percent_used: u64 = (1569494 / 3915755) * 100;
println!("{}", mem_percent_used);
// outputs 0, expecting 40

In python -

print((1569494 / 3915755) * 100)
# output 40.08151684668729

even if it's a simple calculation then also it's giving wrong output.

  • 1
    Rust, I presume, behaves like C as described in the dup. Also, Python 2 and 3 will give you different results as [they changed the rules for integer division](https://stackoverflow.com/q/2958684/1270789). – Ken Y-N Nov 04 '21 at 06:40

1 Answers1

1

That's because rust does not automatically cast data type, unlike python.

Here is a working example:

fn main() {

  let mem_percent_used: f64 = (1569494.0 / 3915755.0) * 100.0;
  println!("{}", mem_percent_used);

}

output:

40.08151684668729
Kristian
  • 2,456
  • 8
  • 23
  • 23