将字符串中的元素串联起来以红色语言浮动
问题描述:
我想将许多可用的十进制数字作为字符串一次性转换为浮动。我想下面的代码将这些字符串组合成一个系列,然后将它们转换为浮动。这适用所有的权利,但失败,如果有一个错误:将字符串中的元素串联起来以红色语言浮动
a: "1.5"
b: ""
c: "3.7"
invars: [a b c]
print a
print type? a
set invars foreach x invars [append [] to-float reduce x] ; code to convert string series to float series;
print a
print type? a
的错误是:
*** Script Error: cannot MAKE/TO float! from: ""
*** Where: to
*** Stack: to-float
纠错,我尝试下面的代码:
temp: []
foreach x invars [
y: copy ""
either error? [set [y] to-float reduce x]
[append temp reduce x] ; put original value if not convertable
[append temp reduce y] ]
print temp
set invars temp
print a
print type? a
不过这也是不工作。问题在哪里?如何纠正?
答
forall invars [invars/1: load get invars/1]
>> invars
== [1.5 [] 3.7]
,如果你想摆脱空块
>> replace/all invars block! 0
== [1.5 0 3.7]
的,如果你真的想要做的一切(:少:)步骤
forall invars [invars/1: either empty? invars/1: get invars/1 [0.0] [load invars/1]]
后,您可以再次设置您的变量。
但如果你想只设置你的变量,你必须做
foreach x invars [set :x load get x]
与漂浮的
foreach x invars [either empty? get x [set :x 0] [set :x to-float get x]]
最后的所有的错误安全版与漂浮的
foreach x invars [attempt [set :x to-float get x]]
== 3.7
>> a
== 1.5
>> b
== ""
>> c
== 3.7
我把“浮动”放在哪里? – rnso
如果您使用带**的解决方案或者是空的** **您可以用**将其替换为**加载**浮动** – sqlab
哪一个不工作?所有版本按照描述工作。使用新的新控制台 – sqlab