patternrustMajor
Dividing two integers doesn't print as a decimal number in Rust
Viewed 0 times
dividingdoesnprintintegersdecimalrustnumbertwo
Problem
I'm learning Rust, but when I print a decimal number, only the integer part is printed, not the decimal part:
but when I print the decimal number explicitly, it works correctly:
fn main(){
println!("{:.3}", 22/7);
}
// This only show 3but when I print the decimal number explicitly, it works correctly:
fn main(){
println!("{:.3}", 0.25648);
}
// this print 0.256Solution
Just like in C and C++, dividing integers results in another integer. Try this C++ program to see:
println!("{:.3}", 22 / 7); // 3
println!("{:.3}", 22.0 / 7.0); // 3.143
}
let x = 22;
println!("{:.3}", x / 7); // 3
println!("{:.3}", x as f32 / 7.0); // 3.143
}
`
#include
using namespace std;
int main()
{
cout
Similarly in Rust, you need to specify both numbers as floats instead, which is done by putting a decimal anywhere in the number. Try this Rust equivalent of the above program:
fn main() {println!("{:.3}", 22 / 7); // 3
println!("{:.3}", 22.0 / 7.0); // 3.143
}
If you have variables, you can convert them with as to either f32 or f64, depending on your needs:
fn main() {let x = 22;
println!("{:.3}", x / 7); // 3
println!("{:.3}", x as f32 / 7.0); // 3.143
}
`
Context
Stack Overflow Q#35097710, score: 85
Revisions (0)
No revisions yet.