【问题标题】:how to sum digits in a multi-digit number Matlab如何将多位数字中的数字相加 Matlab
【发布时间】:2015-01-28 20:37:33
【问题描述】:

我想知道如何在 Matlab 中对多位数字求和。

例如 1241= 1+2+4+1 = 8

【问题讨论】:

  • 网上一定有大量的 Matlab 教程供您阅读。不明白的部分在这里问...

标签: matlab sum digits


【解决方案1】:

基于字符串的答案:

>> n = 1241;
>> sum(int2str(n)-48)

ans =

     8

首先使用int2str将该数字转换为字符串表示形式,然后从字符串中每个元素的ASCII码中减去'0'的ASCII码(即48),生成一个数字向量。然后将其相加得到结果。

【讨论】:

    【解决方案2】:
    A  = 35356536576821;
    A  = abs(A);
    xp = ceil(log10(A)):-1:1;
    
    while ~isscalar(xp)
        A  = sum(fix(mod(A,10.^xp)./10.^[xp(2:end) 0]));
        xp = ceil(log10(A)):-1:1;
    end    
    

    这是数值方法

    【讨论】:

      【解决方案3】:

      这是解决方法是字符的方法:

      A = '35356536576821';
      A = char(regexp(A,'\d+','match'));
      while ~isscalar(A)
          A = num2str(sum(A - '0'));
      end
      

      两者,首先取绝对数(去掉减号)然后:数字计算 log10() 一个数字有多少个数字,并通过模数和除法提取求和的数字,而 char 方法转换为数字隐式转换为- '0' 的数字,求和并再次转换回字符串。

      【讨论】:

        【解决方案4】:

        另一种全算术方法:

        n = 1241;                   %// input
        s = 0;                      %// initiallize output
        while n>0                   %// while there is some digit left
            s = s + mod(n-1,10)+1;  %// sum rightmost digit
            n = floor(n/10);        %// remove that digit
        end
        

        【讨论】:

          【解决方案5】:

          您可以使用此代码

          sum(int2str(n)-48)
          

          其中 n,是您输入的数字。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2013-02-03
            • 2012-04-24
            • 2022-11-12
            • 2020-07-01
            • 1970-01-01
            相关资源
            最近更新 更多