Trait std::ops::Div 1.0.0[−][src]
Expand description
除法运算符 /
。
请注意,默认情况下 Rhs
是 Self
,但这不是强制性的。
Examples
可划分的有理数
use std::ops::Div; // 根据算术的基本定理,最低限度的有理数是唯一的。 // 因此,通过将 `Rational` 保持为简化形式,我们可以得出 `Eq` 和 `PartialEq`。 #[derive(Debug, Eq, PartialEq)] struct Rational { numerator: usize, denominator: usize, } impl Rational { fn new(numerator: usize, denominator: usize) -> Self { if denominator == 0 { panic!("Zero is an invalid denominator!"); } // 用最大公约数除以最低条件。 let gcd = gcd(numerator, denominator); Self { numerator: numerator / gcd, denominator: denominator / gcd, } } } impl Div for Rational { // 有理数的除法是封闭的运算。 type Output = Self; fn div(self, rhs: Self) -> Self::Output { if rhs.numerator == 0 { panic!("Cannot divide by zero-valued `Rational`!"); } let numerator = self.numerator * rhs.denominator; let denominator = self.denominator * rhs.numerator; Self::new(numerator, denominator) } } // 欧几里德 (Euclid) 具有 2000 年历史的算法,用于找到最大公约数。 fn gcd(x: usize, y: usize) -> usize { let mut x = x; let mut y = y; while y != 0 { let t = y; y = x % y; x = t; } x } assert_eq!(Rational::new(1, 2), Rational::new(2, 4)); assert_eq!(Rational::new(1, 2) / Rational::new(3, 4), Rational::new(2, 3));Run
将 vectors 除以线性代数中的标量
use std::ops::Div; struct Scalar { value: f32 } #[derive(Debug, PartialEq)] struct Vector { value: Vec<f32> } impl Div<Scalar> for Vector { type Output = Self; fn div(self, rhs: Scalar) -> Self::Output { Self { value: self.value.iter().map(|v| v / rhs.value).collect() } } } let scalar = Scalar { value: 2f32 }; let vector = Vector { value: vec![2f32, 4f32, 6f32] }; assert_eq!(vector / scalar, Vector { value: vec![1f32, 2f32, 3f32] });Run
Associated Types
Required methods
Implementors
此运算将舍入为零,舍去精确结果的任何小数部分。
Panics
This operation will panic if other == 0
or the division results in overflow.
此运算将舍入为零,舍去精确结果的任何小数部分。
Panics
This operation will panic if other == 0
or the division results in overflow.
此运算将舍入为零,舍去精确结果的任何小数部分。
Panics
This operation will panic if other == 0
or the division results in overflow.
此运算将舍入为零,舍去精确结果的任何小数部分。
Panics
This operation will panic if other == 0
or the division results in overflow.
此运算将舍入为零,舍去精确结果的任何小数部分。
Panics
This operation will panic if other == 0
or the division results in overflow.
此运算将舍入为零,舍去精确结果的任何小数部分。
Panics
This operation will panic if other == 0
or the division results in overflow.