简体   繁体   English

浮点数和零比较

[英]Float number and zero comparison

I have a simple PHP task, to sum all number's digits. 我有一个简单的PHP任务,求和所有数字。

$number = 345;
$digit = $number;
$sum = 0;

while ($number > 0) {
  $digit = $number % 10;
  $sum += $digit;

  $number /= 10;
}

This solution would give correct result. 该解决方案将给出正确的结果。 However, I'm aware that it will enter loop way more than three times . 但是,我知道它将进入循环方式超过3次 And eventually it will become equal to zero. 最终它将变为零。

Why is that happening? 为什么会这样呢? At what time, floats become zero? 在什么时候浮点数变为零? Just by following math principles, this would be an infinite loop, right? 仅遵循数学原理,这将是一个无限循环,对吗? And since there are more than 3, 4 and 5 digits, how end result is not greater than 12 (even for that little amount). 并且由于有超过3、4和5位数字,最终结果如何不大于12(即使是很小的数字)。

PS I know that I should solve this by rounding $number value for example, but I'm just curios about floats and its behaviour. PS我知道我应该通过例如舍入$number值来解决此问题,但我只是对浮点数及其行为的好奇心。

When you update number you should really be doing this 当您更新号码时,您确实应该这样做

$number -= $digit;
$number /= 10;

Floats are platform specific, check out this link http://php.net/manual/en/language.types.float.php 浮点数是特定于平台的,请查看此链接http://php.net/manual/zh/language.types.float.php

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM