程序可以将数字的数字相加,对于较小的数字,但不适用于较大的数字

时间:2016-10-02 12:34:12

标签: php sum

我正在编写一个程序来对数字的数字求和,它适用于小数字,但是对于大数字而言它是否给出了意想不到的总和? 以下是该计划。

<?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

我看到上面的代码结果很好的整数没有但不是双重没有' 请指导我这个问题的完美解决方案是什么?

1 个答案:

答案 0 :(得分:0)

您知道是否添加了新echo $sum->digit_sum(32);输出会显示 62 。导致您创建一次对象并多次调用相同的函数。该对象存储所有时间的总和。

<强>解决方案:

只需在while循环之前添加一个语句$this->sum = 0;即可清除之前的总和。

在线示例: https://3v4l.org/C7Yli

更新:我根据您的评论测试了writephponline.com中的脚本,并获得了以下结果。

enter image description here