zipper01 发表于 2022-7-5 23:59:13

整数舍入问题

你好
我有一个小的取整问题,我就是无法解决。
脚本函数:
 
1) 选择图案填充(获取图案填充区域)
2) 选择属性并填写区域字段值
 
我设法将精度四舍五入到最接近的整数。
尽管我希望取而代之的是四舍五入最接近0.5。
 
例子:
84.1 -> 84
84.6 -> 84.5
84.7 -> 85
 
如果有人能给我指出正确的方向,我会非常高兴。
 

(defun c:arf(/ fStr cObj vObj cTxt vTxt)

(vl-load-com)

(if
   (and
   (setq cObj(entsel "\nPick object with Area property"))
   (vlax-property-available-p
(setq vObj(vlax-ename->vla-object(car cObj))) 'Area)
   ); end and
   (if
   (and
(setq cTxt(nentsel "\nPick Text, MText or Attribute to insert field > "))
(vlax-property-available-p
(setq vTxt(vlax-ename->vla-object(car cTxt))) 'TextString)
); end and
   (progn
   (vla-put-TextString vTxt
(strcat "%<\\AcObjProp Object(%<\\_ObjId "
        (itoa(vla-get-ObjectID vObj)) ">%).Area \\f \"%lu2%pr1%ps%ct8\">%"))
      ); end progn
   ); end if
   ); end if
(princ)
); end of c:arfield

Stefan BMR 发表于 2022-7-6 00:15:37

您可以在字段中使用公式:
(strcat "%<\\AcExpr (0.5*round(%<\\AcObjProp Object(%<\\_ObjId "
               (itoa(vla-get-ObjectID vObj))
               ">%).Area>%" "*1e-6/0.5)) \\f \"%lu2%pr1\">%")

Lee Mac 发表于 2022-7-6 00:20:05

 
为了解决这个问题,我试图使用格式设置为0的嵌套字段来实现舍入(但嵌套字段的格式似乎没有传递到父字段)-我没有意识到“round”在公式字段中是有效的运算符,谢谢Stefan

marko_ribar 发表于 2022-7-6 00:33:58

以下是我的数字舍入函数。。。前2组合用于将以0或5(0,5,10,15,20,…)结尾的第一个最近数上的任何数字四舍五入
 
我的最后一个函数(d轮)是您实际需要的函数。。。只需提供您想要舍入的数字,对于舍入格式的小数,您提供0.5。。。
 

(defun fixx ( n / remi r )
(setq remi (- n (fix n)))
(if (< remi 0.5) (setq r (fix n)))
(if (>= remi 0.5) (setq r (+ (fix n) 1)))
r
)

(defun round ( n / ldig r )
(setq ldig (- n (* (fix (/ n 10.0)) 10)))
(if (< -0.5 ldig 3) (setq r (* (fix (/ n 10.0)) 10)))
(if (< 2 ldig(setq r (+ (* (fix (/ n 10.0)) 10) 5)))
(if (< 7 ldig 9.5) (setq r (+ (* (fix (/ n 10.0)) 10) 10)))
r
)

(round 7.2) => 10
(round 7.3) => 10
(round 7.5) => 10
(round 7.7) => 10
(round 7. => 10

(fixx 7.2) => 7
(fixx 7.3) => 7
(fixx 7.5) => 8
(fixx 7.7) => 8
(fixx 7. => 8

(round (fixx 7.2)) => 5
(round (fixx 7.3)) => 5
(round (fixx 7.5)) => 10
(round (fixx 7.7)) => 10
(round (fixx 7.) => 10

(defun _round ( n d )
(if (< (- n (* (fix (/ n d)) d)) (/ d 2.0))
   (* (fix (/ n d)) d)
   (* (+ 1.0 (fix (/ n d))) d)
)
)

(_round 7.2 0.5) => 7.0
(_round 7.3 0.5) => 7.5
(_round 7.5 0.5) => 7.5
(_round 7.7 0.5) => 7.5
(_round 7.8 0.5) => 8.0

 
虽然你已经有了一个案例(代码)的答案,也许你会发现这些也很有用。。。
 
M、 R。

Stefan BMR 发表于 2022-7-6 00:47:37

那也是我第一次尝试。 
不客气,李。以下是字段和表格公式中可用的其他函数列表。

Lee Mac 发表于 2022-7-6 00:52:53

 
太好了,谢谢

zipper01 发表于 2022-7-6 01:08:00

非常感谢你。
很有魅力!
页: [1]
查看完整版本: 整数舍入问题