编程以查找给定数字的位数之和,直到总和变为单个数字。 (例如,12345 => 1 + 2 + 3 + 4 + 5 = 15 => 1 + 5 = 6)。 [英] Program to find the sum of digits of a given number until the sum becomes a single digit. (e.g. 12345=>1+2+3+4+5=15=>1+5=6) .

查看:130
本文介绍了编程以查找给定数字的位数之和,直到总和变为单个数字。 (例如,12345 => 1 + 2 + 3 + 4 + 5 = 15 => 1 + 5 = 6)。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

编程以查找给定数字的位数之和,直到总和变为单个数字。 (例如12345 => 1 + 2 + 3 + 4 + 5 = 15 => 1 + 5 = 6)。

Program to find the sum of digits of a given number until the sum becomes a single digit. (e.g. 12345=>1+2+3+4+5=15=>1+5=6) .

推荐答案

这听起来像家庭作业,所以没有代码!

但这很简单:

1)创建一个total变量,并将working变量设置为你想要求和的值。 br />
2)创建一个循环,并将总变量设置为零

3)在循环中,将工作变量模10加到总数中。

4)将工作变量除以10

5)如果工作变量大于零,则返回循环(3)

6)如果总变量小于10,你有值。

7)否则,将工作变量设置为总变量,然后绕回循环(2)
This sounds like homework, so no code!
But this is really simple:
1) Create a "total" variable, and set a "working" variable to the value you want to sum.
2) Create a loop, and set the total variable to zero
3) In the loop, add the working variable modulo 10 to the total.
4) Divide the working variable by 10
5) If the working variable is greater than zero then go back round the loop at (3)
6) If the total variable is less than ten, you have the value.
7) Otherwise, set the working variable to the total variable, and go back round the loop at (2)


class Program
    {
        static void Main(string[] args)
        {
            string num = Console.ReadLine();
            int sum = DigitSum(Convert.ToInt32(num));
            Console.WriteLine("sum:{0}", sum);
            Console.Read();
        }
        static private int DigitSum(int num)
        {
            int sum = 0;
            while (num > 0)
            {
                sum += num % 10;
                num /= 10;
            }
            if (sum > 9)
            {
                sum = DigitSum(sum);
            }
            return sum;
        }
    }


这篇关于编程以查找给定数字的位数之和,直到总和变为单个数字。 (例如,12345 => 1 + 2 + 3 + 4 + 5 = 15 => 1 + 5 = 6)。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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