我有一個數組:PHP:求和陣列值的結果是錯誤的
$test =array('49'=> '-0','51'=> '-0','50'=> '0','53'=> '-1.69','55'=> '0','57'=> '-2','59'=> '-6','60'=> '-12','65'=> '0','66'=> '0','67'=> '21.69','69'=> '0','70'=> '0','71'=> '0',);
echo "\n".'===== First Method ========';
echo "\n\n".print_r($test);
echo "\n array_sum: ".array_sum($test);
echo "\n\n".'===== Second Method ========';
$total = 0;foreach($test as $value) $total += $value;
echo "\n foreach:".$total."\n";
結果是
[email protected]:~/Desktop$ php test.php
===== First Method ========Array
(
[49] => -0
[51] => -0
[50] => 0
[53] => -1.69
[55] => 0
[57] => -2
[59] => -6
[60] => -12
[65] => 0
[66] => 0
[67] => 21.69
[69] => 0
[70] => 0
[71] => 0
)
1
array_sum: 3.5527136788005E-15
===== Second Method ========
foreach:3.5527136788005E-15
它是錯誤的,結果應該是0,不3.5527136788E-15,如何解決它?
您應該使用換行符重新格式化該代碼,以使其易於閱讀。另外,首先想到的是,你正在總結可能會遭受鑄造錯誤的字符串。這感覺很像浮點精度錯誤。 –
那麼,男士應該用什麼樣的貝殼? –