TCL incr为零填充整数提供了错误的值
我试图增加一个被零填充的数字,使之成为一个六位数。但奇怪的是,除了一位数以外的任何值都给出了错误的值。像TCL incr为零填充整数提供了错误的值,tcl,increment,Tcl,Increment,我试图增加一个被零填充的数字,使之成为一个六位数。但奇怪的是,除了一位数以外的任何值都给出了错误的值。像 set x 000660 incr x 1 给出结果433。也尝试使用较小的数字,如010,但结果是9。为什么会这样? 解决此问题的正确方法是什么?以0开头的数字 是八位整数。它相当于十进制432 010与十进制中的8相同 要去除零,请尝试以下操作: proc stripzeros {value} { regsub ^0+(.+) $value \\1 retval ret
set x 000660
incr x 1
给出结果433。也尝试使用较小的数字,如010,但结果是9。为什么会这样?
解决此问题的正确方法是什么?以0开头的数字
是八位整数。它相当于十进制432
010与十进制中的8相同
要去除零,请尝试以下操作:
proc stripzeros {value} {
regsub ^0+(.+) $value \\1 retval
return $retval
}
有关详细信息,请参阅。您也可以尝试这种方法
proc getIntVal { x } {
# Using 'scan' command to get the literal integer value
set count [ scan $x %d n ]
if { $count!= 1 } {
return -1
}
return $n
}
proc padZero { x } {
# Using 'format' to pad with leading zeroes.
return [ format "%05d" $x ]
}
set val 00060
puts "Initial value : $val"
set tmp [ getIntVal $val ]; # 'tmp' will have the value as '60'
incr tmp;
set val [ padZero $tmp ]; # Padding with zero now
puts "Final value : $val"
于浩已经解释了八位字节的问题,迪内什添加了一些程序来规避这个问题。我建议创建一个进程,它将接受一个零填充整数,并返回另一个相同格式的零填充整数,其工作原理与incr相同: 用这个
% incr_pad 000660 1
000661
% incr_pad 2.5 1
expected integer but got "2.5"
% incr_pad 02 1.5
expected integer but got "1.5"
% incr_pad 010 2
012
% incr_pad 1 2 3
wrong # args: should be "incr_pad varName ?increment?"
% incr_pad 00024
00025
% incr_pad 999
1000
当然,您可以将函数的名称更改为较短的名称或您认为更合适的名称。如何阻止tcl将其视为octate@Codename_DJ删除前导0是一种选择吗?这是我最明显的方法。但是否有任何标识符或东西可以将其强制表示为整数?@Codename\u DJ我不这么认为。无论如何,请查看我刚才添加的链接,希望它有用。@glennjackman如果val不是数字字符串,代码提取数字部分并继续处理,这是一件好事吗?从我的观点来看,输入值为123abc`和递增后输出值为124似乎是错误的。一种策略是:设置计数[扫描$x%d%s n rest],并处理计数为0、1或2的情况。@glennjackman通常,%d%c效果更好。这是因为它将通过失败处理尾随空格,而%s不会导致失败。OTOH,当Tcl解析一个数字时,它会从中删除空格-我刚刚检查过-所以%d%s可能是正确的选择…
proc incr_pad {val args} {
# Check if increment is given properly
if {[llength $args] == 0} {
set args 1
} elseif {[llength $args] > 1} {
return -code error {wrong # args: should be "incr_pad varName ?increment?"}
}
# Check for integers
if {![regexp {^[0-9]+$} $val]} {
return -code error "expected integer but got \"$val\""
} elseif {![regexp {^[0-9]+$} $args]} {
return -code error "expected integer but got \"$args\""
}
# Get number of digits
set d [regexp -all {[0-9]} $val]
# Trim 0s to the left
set newval [string trimleft $val 0]
# Now use incr
incr newval $args
# Return back the number formatted with the same zero padding as initially given
return [format "%0${d}d" $newval]
}
% incr_pad 000660 1
000661
% incr_pad 2.5 1
expected integer but got "2.5"
% incr_pad 02 1.5
expected integer but got "1.5"
% incr_pad 010 2
012
% incr_pad 1 2 3
wrong # args: should be "incr_pad varName ?increment?"
% incr_pad 00024
00025
% incr_pad 999
1000