将数字四舍五入到最近值
我今天一直在玩弄一些东西,但似乎找不到正确的代码,它将接受一个数字并将其四舍五入到最接近的1/2“。只有当它首先不是一个整数时。3" = 3"
3.25" = 3.5"
4" = 4"
4.625" = 5"
等 粗略方法:
(defun Round05( theNumber / theRem )
(setq theRem (rem theNumber 1))
(cond
((= theRem 0.0) theNumber)
((and (> theRem0.0)(< theRem 0.25)) (* (fix theNumber) 1.0))
((and (>= theRem 0.25) (< theRem 0.75)) (+ (fix theNumber) 0.5))
((>= theRem 0.75) (+ (fix theNumber) 1.0))
)
)
也可以进一步细化以适用于负值。 MSasu,
非常感谢。我在VB中创建了一个很好的函数。NET在几周前完成了这项工作,但在将其应用于LISP时遇到了一些困难。这非常有效。 很高兴听到这对你有用;不客气!
出于好奇,有什么东西不能从VB代码中翻译出来? 另一个版本也接受否定:
;; Round Up-Lee Mac
;; Rounds 'n' up to the nearest 'm'
(defun LM:roundup ( n m )
(cond ((equal 0.0 (rem n m) 1e- n)
((< n 0) (- n (rem n m)))
((+ n (- m (rem n m))))
)
)
_$ (LM:roundup 3 0.5)
3
_$ (LM:roundup 3.25 0.5)
3.5
_$ (LM:roundup 4 0.5)
4
_$ (LM:roundup 4.625 0.5)
5.0 另一个版本
(defun round (num prec)
(* prec
(if (minusp num)
(fix (- (/ num prec) 0.5))
(fix (+ (/ num prec) 0.5))
)
)
)
谢谢大家。我现在有很多函数。我将修补转换我的VB。NET代码。我稍后会发布结果。
VB。网络代码
' This handles any non-integer input and rounds the user's input up to the nearest vDenominator
' In this case we use 1/16" and it remember it rounds up, not down.
Public Function RoundFraction(ByVal x As Double, ByVal vDenominator As Integer) As Double
If (x - Int(x)) * vDenominator <> Int((x - Int(x)) * vDenominator) Then
x = (Int((x - Int(x)) * vDenominator) + 1) / vDenominator + Int(x)
End If
Return x
End Function
我这样称呼它:
RoundFraction(4.4231, 16)
结果是4.4375。这纠正了当用户输入一个奇怪的维度,该维度至少足够接近他们想要的。
页:
[1]