+ 2

Rust calculation

let percentage = (2 / 4) * 100; println!("{}%", tust); Why that percentage variable give me 0 result instead of 50, is this a bug? In other programing language like JavaScript it return 50, can anyone explain why this happened in rust?

11th Feb 2022, 11:40 AM
EsaKurniawan
3 ответов
+ 4
But, it returns the same(0) in other languages like C,Java, etc. The reason that it happens is because you're doing integer/integer division here. a/b gives you 0 if b>a. Try changing one of them into a float and see the output.
11th Feb 2022, 12:21 PM
Simba
Simba - avatar
+ 1
Unlike other languages, we have to cast all values to work in rust. let result = (float_number/4.0)*100.0
11th Feb 2022, 2:12 PM
Simba
Simba - avatar
0
Still error when i tried this code below let number = 3; let float_number = number as f64; let result = (float_number / 4) * 100; println!("{}", result);
11th Feb 2022, 1:25 PM
EsaKurniawan