对于 TCL 中的非整数循环递增

For loop increment by a non-integer in TCL

我想在TCL中实现以下C代码:

Float power_pitch = 8
float offset = 7.5
float threshold = 100 
for(i=power_pitch+offset ; i<= threshold ; i += power_pitch)

我想在TCL中实现上面的forloop。我在 TCL 中尝试了以下代码:

set power_pitch 8
set offset 7.5
set threshold 100
for { set i [expr $power_pitch + $offset] } { $i <= $threshold } { incr i $power_pitch}

但是当我执行上面的代码时,出现以下错误:

expected integer but got "15.5 " while executing incr i $power_pitch

你能帮我在TCL中实现上面的forloop吗?

incr 命令仅适用于整数。否则,使用:

set i [expr {$i + $power_pitch}]

for 命令本身不会介意。 (注意浮点数舍入问题;它们不是特定于 Tcl 的,但可以命中任何不是 2 的整数倍的整数倍……)

Donal已经给出了问题的答案,我想对for命令说两点看法。

  1. for 非常接近 free-form
  2. 虽然整数计数循环是 for 的典型用途,但它绝不是唯一的选择

for命令有概要

for start test next body

其中 startnextbody 是命令字符串 (即适合作为 eval 的参数;它们可以是空的,包含单个命令,或者是完整的脚本)并且 test 是一个布尔表达式字符串(即适合作为参数expr 评估为或可以被强制转换为布尔值的东西。

通常,start用于设置testbody,并且 next 应该使状态逐渐接近 test return 一个错误的值,但这只是一个约定,不是要求。以下是完全有效(但相当臭)的调用:

for {set n 0 ; puts -nonewline X} {[incr n] < 5} {puts -nonewline X} {
    puts -nonewline [string repeat - $n]
}

for {set f [open foo.txt] ; set n 0} {$n >= 0} {puts $line} {
    set n [chan gets $f line]
}

for 命令字符串和布尔表达式的任意组合,它将 运行。它可能会永远执行它的 body,甚至一次都不会执行,但它会 运行。不要局限于 for {set i 0} {$i < 10} {incr i} {...} 调用,那是 1950 年代的想法。

即使你只是想用它来计算循环次数,也有很多选择,例如:

for {set i 0} {$i < $limit} {incr i} {...}             ;# simple increment
for {set i 0} {$i < $limit} {incr i $n} {...}          ;# stepping increment/decrement
for {set i 0} {$i < $limit} {incr i $i} {...}          ;# doubling increment
for {set i 0} {$i < $limit} {set i [expr {...}]} {...} ;# arbitrary change

放开你的心,剩下的会随之而来。

文档:chan, expr, for, incr, open, puts, set, string