Advertisement
cwchen

[Rust] The constructor of Rational class

Sep 4th, 2017
3,167
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Rust 0.41 KB | None | 0 0
  1. impl Rational {
  2.     pub fn new(p: i32, q: i32) -> Rational {
  3.         if q == 0 {
  4.             panic!("Denominator should not be zero.");
  5.         }
  6.  
  7.         let d = Rational::gcd(p, q).abs();
  8.  
  9.         Rational{ num: p / d, denom: q / d }
  10.     }
  11. }
  12.  
  13. impl Rational {
  14.     fn gcd(a: i32, b: i32) -> i32 {
  15.         if b == 0 {
  16.             a
  17.         } else {
  18.             Rational::gcd(b, a % b)
  19.         }
  20.     }
  21. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement