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

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-24 00: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 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?
  • ¥15 matlab(相关搜索:紧聚焦)
  • ¥15 基于51单片机的厨房煤气泄露检测报警系统设计
  • ¥15 Arduino无法同时连接多个hx711模块,如何解决?