求和时出现 Tcl 错误

Tcl error in doing sum

我想计算存储在 tcl 列表 P 中的数字列表的平均值。这是我的脚本:

set sum 0.0
foreach e $P { set sum [expr {$sum + $e}] }
set avg [expr {1.0*$sum / [llength $P]}]

但我有错误:can't use non-numeric string as operand of "+" 我该怎么做?

您的问题可能是由于 P 中的某些元素不是数字。无论如何,这就是您计算平均值的方式:

package require math::statistics
::math::statistics::mean $P

假设 P 是一个数字列表。

如果你有一个数据项列表,想知道其中是否有不适合 expr 算法的,你可以这样做:

foreach n $data {
    if {![string is double -strict $n]} {
        error "$n is not a number"
    }
}

这将报告第一个非数字。 string is double命令识别整数和浮点数1。如果您省略 -strict 标志,空字符串将被视为数字(expr 仍然会阻塞它,尽管 2)。

这将为您提供 $data 中所有非数字项目的子列表:

lmap n $data { 
    if {![string is double -strict $n]} {set n} continue
}

这将为您提供 $data 中所有适当编号项目的子列表:

lmap n $data { 
    if {[string is double -strict $n]} {set n} continue
}


1 名称"double" 表示它returns 对任何可以翻译成C 数据类型double 的字符串都成立,它特指存储双精度浮点数(浮点数编码行业标准)。如果你不知道那是什么,你可以假装它的意思是 "both numbers that look like integers and numbers that look like reals".

中的 double

2 expr 也会阻塞值 NaN 这是一个完全有效的浮点值,它只代表 "not a number" .

文档:continue, error, expr, foreach, if, lmap, math::statistics package, package, set, string