如何总结整数的个别数字? [英] How to sum individual digits of integer?

查看:110
本文介绍了如何总结整数的个别数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个整数值(例如:723),我想加起来所有的值在这个整数,直到我得到一个值

 例如:7 + 2 + 3 = 12
    1 + 2 = 3

我是新的C#。请给我你的答案的一个很好的解释,以及:)


解决方案

  INT I = 723;
INT ACC;
做{
    ACC = 0;
    而(ⅰ大于0)
    {
        ACC +我= 10%;
        I / = 10;
    }
    I = ACC;
}而(ACC> = 10);

10%给出最终数字各一次,所以我们添加到累加器。 / = 10 执行整数除法,每次除去基本上最后一位。然后,我们重复,直到我们有足够小的数目。

I have an integer value (ex: 723) and i want to add up all the values in this integer until i get a single value.

ex: 7 + 2 + 3 = 12
    1 + 2     = 3

I'm new to C#. please give me a good explanation of your answer as well :)

解决方案

int i = 723;
int acc;
do {
    acc = 0;
    while (i > 0)
    {
        acc += i % 10;
        i /= 10;
    }
    i = acc;
} while(acc>=10);

% 10 gives the final digit each time, so we add that into an accumulator. /= 10 performs integer division, essentially removing the final digit each time. Then we repeat until we have a small enough number.

这篇关于如何总结整数的个别数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆