Rust calculation | Sololearn: Learn to code for FREE!

+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?

2/11/2022 11:40:38 AM

EsaKurniawan

3 Answers

New Answer

+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.

+1

Unlike other languages, we have to cast all values to work in rust. let result = (float_number/4.0)*100.0

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);