- Difference between modulo and remainder. The modulo operator (`%`) always has the sign of the divisor, whereas remainder has the sign of the dividend. - 取模:符号跟**除数**一样 - 取余:符号跟**被除数**一样 | a | b | a.divmod(b) | a/b | a.modulo(b) | a.remainder(b) | |---|---|---|---|---|---| |13|4|3,|1|3|1|1| |13|-4|-4,|-3|-4|-3|1| |-13|4|-4,|3|-4|3|-1| |-13|-4|3,|-1|3|-1|-1| |11.5|4|2.0,|3.5|2.875|3.5|3.5| |11.5|-4|-3.0,|-0.5|-2.875|-0.5|3.5| |-11.5|4|-3.0,|0.5|-2.875|0.5|-3.5| |-11.5|-4|2.0,|-3.5|2.875|-3.5|-3.5| # In Rust - The remainder has the same sign as the dividend and is computed as: - `x - (x / y).trunc() * y` - `tunc()`表示向零的方向取整 - 结果的符号与被除数一样 - Example: ```rust let x: f32 = 50.50; let y: f32 = 8.125; let remainder = x - (x / y).trunc() * y; // The answer to both operations is 1.75 assert_eq!(x % y, remainder); ``` # References - https://ruby-doc.com/docs/ProgrammingRuby/html/ref_c_numeric.html - https://doc.rust-lang.org/src/core/ops/arith.rs.html#590