ActiveState Perl 5.14无法比较某些值?

基本上,在文件stream上使用下面的代码,我得到以下内容:

$basis = $2 * 1.0; $cost = ($basis - 2500.0) ** 1.05; # The above should ensure that both cost & basis are floats printf " %f -> %f", $basis, $cost; if ($basis gt $cost) { # <- *** THIS WAS MY ERROR: gt forces lexical! $cost = $basis; printf " -> %f", $cost; } 

输出:

  10667.000000 -> 12813.438340 30667.000000 -> 47014.045519 26667.000000 -> 40029.842300 66667.000000 -> 111603.373367 -> 66667.000000 8000.000000 -> 8460.203780 10667.000000 -> 12813.438340 73333.000000 -> 123807.632158 -> 73333.000000 6667.000000 -> 6321.420427 -> 6667.000000 80000.000000 -> 136071.379474 -> 80000.000000 

正如你所看到的,对于大多数的值,代码看起来工作正常。

但对于一些值… 66667,80000,和其他一些,ActivePerl 5.14告诉我,66667> 1111603!

有没有人知道这件事 – 或者可以使用一个替代的Perl解释器(Windows)。 因为这太可笑了。

你正在使用词法比较而不是数字

 $cost = ($basis - 2500.0) ** 1.05; printf " %f -> %f", $basis, $cost; if ($basis > $cost) { $cost = $basis; printf " -> %f", $cost; } 

ps:修改为匹配更新的问题

Learning Perl的前几章将为您解决这个问题。 标量值可以是字符串或数字,也可以是两者同时。 Perl使用操作符来决定如何处理它们。 如果你想做数字比较,你可以使用数字比较运算符。 如果你想做字符串比较,你可以使用字符串比较运算符。

标量值本身不具有类型,尽管其他答案和评论使用诸如“float”和“cast”之类的词。 这只是字符串和数字。

不知道为什么你需要比较词法,但你可以强制使用sprintf

 $basis_real = sprintf("%015.6f",$basis); $cost_real = sprintf("%015.6f",$cost); printf " %s -> %s", $basis_real, $cost_real; if ($basis_real gt $cost_real) { $cost = $basis; printf " -> %015.6f", $cost; } 

输出:

  00010667.000000 -> 00012813.438340 00030667.000000 -> 00047014.045519 00026667.000000 -> 00040029.842300 00066667.000000 -> 00111603.373367 00008000.000000 -> 00008460.203780 00010667.000000 -> 00012813.438340 00073333.000000 -> 00123807.632158 00006667.000000 -> 00006321.420427 -> 00006667.000000 00080000.000000 -> 00136071.379474 

如你所述,它的失败原因在于词法比较对字符进行比较,所以当它在6667.点击小数点时,它实际上在6667.之前是按字母顺序111603. ,所以它比较大。

要解决这个问题,你必须使所有的数字相同的大小,特别是在小数点以上的地方。 %015是数字的总大小,包括句点和小数。