You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

AppleScript的repeat with循环如何设置小于1的小数步长,例如0.1?

问题结论

AppleScript 内置的 repeat with 循环语法不支持非整数步长设置,你需要使用变通方案实现从1到2、步长0.1的递增需求。

原生的repeat with i from x to y by step语法中,step参数仅支持整数类型,直接传入0.1会触发语法错误,以下是两种常用的可行实现方案:


方案1:整数循环映射法

用整数循环遍历1到10,再将整数映射为对应的小数,这种方案可以避免浮点数累加带来的精度问题,是更推荐的写法:

repeat with n from 1 to 10
    set i to (n / 10) + 0.9
    log i
end repeat

输出符合预期:

(*1.0*)
(*1.1*)
(*1.2*)
(*1.3*)
(*1.4*)
(*1.5*)
(*1.6*)
(*1.7*)
(*1.8*)
(*1.9*)
(*2.0*)

方案2:while 循环自定义控制变量

如果需要更灵活的步长调整,可以自己初始化变量,用repeat while控制循环终止条件:

set i to 1.0
repeat while i ≤ 2.0
    log i
    set i to i + 0.1
    -- 可选:增加精度修正,避免浮点数累加误差
    set i to (round (i * 10)) / 10
end repeat

这个写法效果和方案1一致,适合步长需要动态调整的场景。


内容的提问来源于stack exchange,提问作者gurkensaas

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 15:24:00