dongshenjie3055 2013-06-13 16:48
浏览 61
已采纳

为什么我的for循环功能不像我期望的那样? [关闭]

I can't find the reson for the following out put from for loop.

for loop

for($i=5; $i>0; $i=$i-.1){
echo $i.'<br>';
}

result is,

5
4.9
4.8
4.7
4.6
4.5
4.4
4.3
4.2
4.1
4
3.9
3.8
3.7
3.6
3.5
3.4
3.3
3.2
3.1
3
2.9
2.8
2.7
2.6
2.5
2.4
2.3
2.2
2.1
2
1.9
1.8
1.7
1.6
1.5
1.4
1.3
1.2
1.1
1
0.9
0.8
0.7
0.6
0.5
0.4
0.3
0.2
0.1
1.0269562977783E-15

why does it print 1.0269562977783E-15? For me it should be quite before 0 that is after .1

  • 写回答

2条回答 默认 最新

  • douzhuo8871 2013-06-13 16:52
    关注

    First of all, 0.1 is the worst enemy of binary float point because there is no accurate way to represent it. There are a lot of decimal point number that cannot be accurately represent with binary float point. In this case, you can adjust your loop to

    for($i = 50; $i > 0; $i = $i - 1){
      echo $i / 10.0 . '<br>';
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作