【问题标题】:Program to sum the digits of a number working fine for small numbers but not for larger-ones程序将数字的数字相加,对于小数但不适用于大数
【发布时间】: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,您将看到您的代码将按预期工作。

标签: php sum


【解决方案1】:

你知道如果你把一个新的echo $sum-&gt;digit_sum(32); 输出会显示你62。因为您创建一次对象并多次调用相同的函数。该对象存储所有时间的总和。

解决方案:

只需要在while循环前加上$this-&gt;sum = 0;的语句就可以清除之前的总和。

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

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

【讨论】:

  • 是的,你是对的,但我有 php 7 ,$sum->digit_sum(3253435674) 给我 36 而不是 42。我在writephponline.com 上检查此代码,结果是相同代码的 42 .
  • 在线示例的输出是什么? 5.6.0 - 5.6.26、hhvm-3.10.0 - 3.14.4、7.0.0 - 7.1.0RC3 的输出,在这些版本中,输出将相同。
猜你喜欢
  • 1970-01-01
  • 2014-07-13
  • 1970-01-01
  • 2021-03-22
  • 1970-01-01
  • 2016-01-31
  • 1970-01-01
  • 2013-09-08
  • 1970-01-01
相关资源
最近更新 更多