Paint Calculator
Given the size of a room and the amount of paint needed to paint a square feet of ceiling, calculate the total amount of paint needed. You can only buy a whole number of gallons of paint.
In this exercise, we need to perform rounding up a number instead of rounding down. The calculation itself is easy:
#![allow(unused)] fn main() { let area_ft2 = length_ft * width_ft; let required_paint: u64 = (area_ft2 / paint_per_ft2).ceil() as u64; }
The remaining part is to print the result:
#![allow(unused)] fn main() { println!( "You will need to purchase {} {} of paint to cover {} square {}.", required_paint, find_noun_form(required_paint, "gallons"), area_ft2, find_noun_form(area_ft2, "foot") ); }
And here are the functions to pluralize a word:
#![allow(unused)] fn main() { fn pluralize(word: &str) -> String { match word { "foot" => "feet".to_string(), _ => word.to_owned() + "s", } } }
#![allow(unused)] fn main() { trait HasOne { const ONE: Self; } impl HasOne for u64 { const ONE: u64 = 1; } impl HasOne for f64 { const ONE: f64 = 1.0; } fn find_noun_form<T>(count: T, word: &str) -> String where T: HasOne + std::cmp::PartialOrd, { if count > T::ONE { pluralize(word) } else { word.to_string() } } }
Notice how we use HasOne trait to write a generic find_noun_form
function that accepts both u64 and f64 as the first parameter.
In addition, we use associated constant feature
to declare the ONE constant for different number types.
In practice, we could use the num crate instead.