Tcl 无法以二进制格式保存浮点数
Tcl could not save floating point numbers in binary format
我正在尝试以二进制格式(浮点数)保存数字列表
但是 Tcl 无法正确保存它,当我从 vb.net
读取文件时我无法获得正确的数字
set outfile6 [open "btest2.txt" w+]
fconfigure stdout -translation binary -encoding binary
set aa {}
set p 0
for {set i 1} {$i <= 1000 } {incr i} {
lappend aa [expr (1000.0/$i )]
puts -nonewline $outfile6 [binary format "f" [lindex $aa $p]]
incr p
}
close $outfile6
Tcl cant save it correctly
您的代码段中有两个问题:
-
lindex
周围的嵌套命令评估缺少括号(请参阅我的评论):[lindex $aa $p]
- 您
fconfigure
d stdout
,而不是您的文件频道:fconfigure $outfile6 -translation binary
修复此问题后,以下内容对我有用:
set outfile6 [open "btest2.txt" w+]
fconfigure $outfile6 -translation binary
set aa {}
set p 0
for {set i 1} {$i <= 1000 } {incr i} {
lappend aa [expr (1000.0/$i )]
puts -nonewline $outfile6 [binary format "f" [lindex $aa $p]]
incr p
}
close $outfile6
改进建议
你的代码片段对我来说似乎过于复杂,尤其是。循环构造。简化为:
- 最好使用
[scan %f $value]
将值显式转换为浮点表示,而不是 [expr]
?
- [二进制格式] 采用计数器或通配符,如
f*
,以处理多个值:[binary format "f*" $aa]
- 你不需要循环变量
p
,使用[lindex $aa end]
;或更好的循环变量来保存单个添加的元素(而不是再次从列表中收集它)。
-translation binary
表示 -encoding binary
我正在尝试以二进制格式(浮点数)保存数字列表 但是 Tcl 无法正确保存它,当我从 vb.net
读取文件时我无法获得正确的数字set outfile6 [open "btest2.txt" w+]
fconfigure stdout -translation binary -encoding binary
set aa {}
set p 0
for {set i 1} {$i <= 1000 } {incr i} {
lappend aa [expr (1000.0/$i )]
puts -nonewline $outfile6 [binary format "f" [lindex $aa $p]]
incr p
}
close $outfile6
Tcl cant save it correctly
您的代码段中有两个问题:
-
lindex
周围的嵌套命令评估缺少括号(请参阅我的评论):[lindex $aa $p]
- 您
fconfigure
dstdout
,而不是您的文件频道:fconfigure $outfile6 -translation binary
修复此问题后,以下内容对我有用:
set outfile6 [open "btest2.txt" w+]
fconfigure $outfile6 -translation binary
set aa {}
set p 0
for {set i 1} {$i <= 1000 } {incr i} {
lappend aa [expr (1000.0/$i )]
puts -nonewline $outfile6 [binary format "f" [lindex $aa $p]]
incr p
}
close $outfile6
改进建议
你的代码片段对我来说似乎过于复杂,尤其是。循环构造。简化为:
- 最好使用
[scan %f $value]
将值显式转换为浮点表示,而不是[expr]
? - [二进制格式] 采用计数器或通配符,如
f*
,以处理多个值:[binary format "f*" $aa]
- 你不需要循环变量
p
,使用[lindex $aa end]
;或更好的循环变量来保存单个添加的元素(而不是再次从列表中收集它)。 -translation binary
表示-encoding binary