admin管理员组

文章数量:1410674

I have a total of 750 count. And each set is 5. Instead of doing many for loop, for {set i 0} {i < 5}, for {set i 5} {i < 10}, for {set i 10} {i < 15}..... Every 5 count, will insert "GOOD".

for {set i 0} {i < 750} {incr i} {
puts $i
if { i * 15} {
puts GOOD
}

Here is the output I am expecting:

0 1 2 3 4 GOOD

5 6 7 8 9 GOOD

10 11 12 13 14 GOOD

15 16 17 18 19 GOOD

Last output 745 746 747 748 749 GOOD

I have a total of 750 count. And each set is 5. Instead of doing many for loop, for {set i 0} {i < 5}, for {set i 5} {i < 10}, for {set i 10} {i < 15}..... Every 5 count, will insert "GOOD".

for {set i 0} {i < 750} {incr i} {
puts $i
if { i * 15} {
puts GOOD
}

Here is the output I am expecting:

0 1 2 3 4 GOOD

5 6 7 8 9 GOOD

10 11 12 13 14 GOOD

15 16 17 18 19 GOOD

Last output 745 746 747 748 749 GOOD

Share Improve this question edited Mar 7 at 9:03 Chang asked Mar 7 at 8:17 ChangChang 12 bronze badges 2
  • I am not an expert in TCL but it looks like you use the same counter variable in an nested loop. What happens if you set the second "i" to "j" as example? so the second loop states: for{set j 0) {j<5} {incr j} {puts $j} – LMA Commented Mar 7 at 8:25
  • Your code is incomplete - missing closing } – thomas Commented Mar 13 at 7:03
Add a comment  | 

2 Answers 2

Reset to default 1

Your main problem seems to be using the wrong condition; $i * 15 will be true for every non-zero value of i (Tcl interprets non-zero numbers as true). I think you are more likely to want $i % 5 == 4, which checks if the remainder of dividing the value in i by 5 is 4.

for {set i 0} {$i < 750} {incr i} {
    puts -nonewline "$i "
    if { $i % 5 == 4 && $i != 0} {
    puts "GOOD "
    }
}

added two conditions. and use nonewline to get your ouput format.

$i % 5 == 4 && $i != 0

本文标签: for loop with increment tclStack Overflow