【发布时间】:2016-02-15 19:55:09
【问题描述】:
下面的代码应该为给定的数字返回阶乘 Tcl 脚本使用递归过程作为输入参数。
if {$argc !=1} {
puts stderr "Error! ns called with wrong number of arguments! ($argc)"
exit 1
} else {
set f [lindex $argv 0]
}
proc Fact {x} {
if { $x==1 } {
return 1
}
return $x * Fact ($x-1)
}
set res [Fact $f]
puts "Factorial of $f is $res"
但是,它没有给出如下所示的输出:$ tclsh fact.tcl 5
Factorial of 5 is
我也尝试过return [expr $x * Fact ($x-1)],但它会导致解析错误。我不知道我是否想念 Tcl 中的递归调用。
【问题讨论】:
-
试试
return [expr {$x * [Fact [expr {$x-1}]}]。我稍后会解释为什么... -
@JohannesKuhn,
return [expr {$x * [Fact [expr {$x-1}]]}]工作,但这种语法有点奇怪,有这么多括号。 -
Tcl 不是从 algol 语法派生的语言。它看起来不像其他语言。