douliang1900 2013-08-23 15:56
浏览 283
已采纳

php:sum数组值的结果是错误的

I have an array:

$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 "
".'===== First Method ========';
echo "

".print_r($test);
echo "
 array_sum: ".array_sum($test);
echo "

".'===== Second Method ========';

$total = 0;foreach($test as $value) $total += $value;
echo "
 foreach:".$total."
";

the result is

gd@gd:~/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

it is wrong, the result should be 0, not 3.5527136788E-15, how to fix it ?

展开全部

  • 写回答

4条回答 默认 最新

  • doufang2228 2013-08-23 16:03
    关注

    This is just your standard floating point arithmetic precision error.

    php -r "echo -1.69 + -2 + -6 + -12 +21.69;"
    3.5527136788005E-15%
    

    You can fix it by using ints rather than floats. For example, if you always expect 2 digits of precision, multiply all your numbers by 100, round them off to ints, sum them, and divide by 100.

    php -r "echo (-169 + -200 -1200 +2169 + -600) / 100;"
    0%                                               
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)
编辑
预览

报告相同问题?

悬赏问题

  • ¥15 KeiI中头文件找不到怎么解决
  • ¥15 QT6将音频采样数据转PCM
  • ¥15 本地安装org.Hs.eg.dby一直这样的图片报错如何解决?
  • ¥15 下面三个文件分别是OFDM波形的数据,我的思路公式和我写的成像算法代码,有没有人能帮我改一改,如何解决?
  • ¥15 Ubuntu打开gazebo模型调不出来,如何解决?
  • ¥100 有chang请一位会arm和dsp的朋友解读一个工程
  • ¥50 求代做一个阿里云百炼的小实验
  • ¥15 查询优化:A表100000行,B表2000 行,内存页大小只有20页,运行时3页,设计两个表等值连接的最简单的算法
  • ¥15 led数码显示控制(标签-流程图)
  • ¥20 为什么在复位后出现错误帧