2020-03-21

Tcl: print number

Write a program that displays the digits from 1 to n then back down to 1; for instance, if n = 5, the program should display 123454321. You are permitted to use only a single for loop. The range is 0 < n < 10.

if {$argc >= 1} {
    set n [lindex $argv 0]
} elseif {$argc == 0} {
    puts "Please input a number."
    exit
}

if {[string is integer $n]==0} {
    puts "It is not a number."
    exit
}

switch $n {
    {1} {puts "1"}
    {2} {puts "121"}
    {3} {puts "12321"}
    {4} {puts "1234321"}
    {5} {puts "123454321"}
    {6} {puts "12345654321"}
    {7} {puts "1234567654321"}
    {8} {puts "123456787654321"}
    {9} {puts "12345678987654321"}
    default {puts "Please input 0 < n < 10"}
}

使用 while 實作的話:
if {$argc >= 1} {
    set n [lindex $argv 0]
} elseif {$argc == 0} {
    puts "Please input a number."
    exit
}

if {[string is integer $n]==0} {
    puts "It is not a number."
    exit
}

if {$n < 1 || $n > 9} {
    puts "Please input 0 < n < 10"
    exit    
}

set positive 1
set count 0
while {1} {
   if {$positive == 1} {
       incr count
       puts -nonewline $count
       if {$count == $n} {
            set positive 0
            continue
       }
   } else {
       incr count -1
       if {$count > 0} {
            puts -nonewline $count
       } else {
            break 
       }
   }
}
puts ""

沒有留言: