2020-04-25

Tcl: loop (calculates the Harmonic series)

用來練習迴圈的問題。

#!/usr/bin/env tclsh
#
# Calculates the Harmonic series.
# h(n) = 1 + 1/2 + 1/3 + … + 1/n
#

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
}

set h 0.0
for {set count $N} {$count >= 1} {incr count -1} {
    set h [expr $h + 1.0 / $count]
}

puts [format "%5E" $h]

再來是使用 while 迴圈計算 Harmonic series 的程式:
#!/usr/bin/env tclsh
#
# Calculates the Harmonic series.
# h(n) = 1 + 1/2 + 1/3 + … + 1/n
#

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
}

set h 0.0
set I 1
while {$I <= $N} {
    set h [expr $h + 1.0 / $I]
    incr I
}

puts [format "%5E" $h]

沒有留言: