【发布时间】:2016-10-02 12:34:12
【问题描述】:
我正在编写一个程序来对数字的数字求和,它对小数字工作正常,但对于大数字,它给出了意外的总和? 下面是程序。
<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
class demo {
private $sum = 0;
private $num = 0;
private $rem = 0;
public function digit_sum($digit) {
//echo gettype($digit).'<br>';
try {
if (gettype($digit) == 'string') {
throw new Exception($digit . ' is not a valid number <br>');
} else {
$this->num = $digit;
while ($this->num > 0) {
$this->rem = $this->num % 10;
$this->sum = $this->sum + $this->rem;
$this->num = $this->num / 10;
}
return "Sum of no $digit is = " . $this->sum . '<br>';
}
} catch (Exception $e) {
echo $e->getMessage();
}
}
}
$sum = new demo();
echo $sum->digit_sum('sfsdfsdfds');
echo $sum->digit_sum(12345);
// outputs correct sum
echo $sum->digit_sum(3253435674);
//outputs incorrect sum
我看到上面的代码结果对整数没有很好,但对于双精度没有' 请指导我解决这个问题的完美方法是什么?
【问题讨论】:
-
我建议您使用更具描述性的变量名称。
-
您的代码也没有为 6 位数字提供正确的值。
-
它产生->没有 123456 的总和是 = 36
-
这就是您的代码失败的原因 stackoverflow.com/a/18055922/1415724 -
3253435674大于 32 位机器上的最大值2147483647。如果您删除其中的4,您将看到您的代码将按预期工作。