跳轉到內容

Rebol 程式設計/round

來自華夏公益教科書,開放的書籍,為開放的世界
ROUND n /even /down /half-down /floor /ceiling /half-ceiling /to scale 

返回最接近的整數。預設情況下,一半向上取整(遠離零)。

ROUND 是一個函式值。

  • n -- 要舍入的值(型別:數字、貨幣、時間)
  • /even -- 一半舍入到偶數結果
  • /down -- 舍入到零,忽略丟棄的數字。(截斷)
  • /half-down -- 一半舍入到零
  • /floor -- 負方向舍入
  • /ceiling -- 正方向舍入
  • /half-ceiling -- 一半舍入到正方向
  • /to -- 返回最接近的刻度引數倍數
    • scale -- 必須是非零值(型別:數字、貨幣、時間)

(特殊屬性)

[編輯 | 編輯原始碼]
  • 捕獲

原始碼

[編輯 | 編輯原始碼]
round: func [
    {Returns the nearest integer. Halves round up (away from zero) by default.} 
    [catch] 
    n [number! money! time!] "The value to round" 
    /even "Halves round toward even results" 
    /down {Round toward zero, ignoring discarded digits. (truncate)} 
    /half-down "Halves round toward zero" 
    /floor "Round in negative direction" 
    /ceiling "Round in positive direction" 
    /half-ceiling "Halves round in positive direction" 
    /to "Return the nearest multiple of the scale parameter" 
    scale [number! money! time!] "Must be a non-zero value" 
    /local m
][
    throw-on-error [
        scale: abs any [scale 1] 
        any [number? n scale: make n scale] 
        make scale either any [even half-ceiling] [
            m: 0.5 * scale + n 
            any [
                all [
                    m = m: m - mod m scale 
                    even 
                    positive? m - n 
                    m - mod m scale + scale
                ] 
                m
            ]
        ] [
            any [
                floor 
                ceiling 
                (ceiling: (found? half-down) xor negative? n down) 
                n: add n scale * pick [-0.5 0.5] ceiling
            ] 
            either ceiling [n + mod negate n scale] [n - mod n scale]
        ]
    ]
]
華夏公益教科書