提交 07ffe68a 编写于 作者: D David Rajchenbach-Teller 提交者: Brian Anderson

uint.rs: added functions div_ceil, div_floor, div_round

上级 f4399063
......@@ -34,6 +34,29 @@
/* Function: div */
pure fn div(x: uint, y: uint) -> uint { ret x / y; }
/**
* Divide two numbers, return the result, rounded up.
*/
pure fn div_ceil(x: uint, y: uint) -> uint {
let div = div(x, y);
if x % y == 0u { ret div;}
else { ret div + 1u; }
}
/**
* Divide two numbers, return the result, rounded to the closest integer.
*/
pure fn div_round(x: uint, y: uint) -> uint {
let div = div(x, y);
if x % y * 2u < y { ret div;}
else { ret div + 1u; }
}
/**
* Divide two numbers, return the result, rounded down.
*/
pure fn div_floor(x: uint, y: uint) -> uint { ret x / y; }
/* Function: rem */
pure fn rem(x: uint, y: uint) -> uint { ret x % y; }
......
......@@ -102,3 +102,10 @@ fn test_overflows() {
assert (uint::min_value() <= 0u);
assert (uint::min_value() + uint::max_value() + 1u == 0u);
}
#[test]
fn test_div() {
assert(uint::div_floor(3u, 4u) == 0u);
assert(uint::div_ceil(3u, 4u) == 1u);
assert(uint::div_round(3u, 4u) == 1u);
}
\ No newline at end of file
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册