我的程序太长。我想使用循环方法来缩短它

时间:2019-04-21 01:11:00

标签: c#

我想从我的生日中找到一个幸运数字,例如:1985年6月7日。我的生日幸运数字1 + 9 + 8 + 5 + 6 + 7 = 36 >> 3 + 6 =9。我的幸运数字是9.我尝试编码。我在编码时使用了4次。我想缩短它,我想获取任何长度数字的数字总和。怎么编码?

c#

private void btn_lucky_Click(object sender, EventArgs e)
        {
            string Bday = dateTimePicker1.Text.Replace("-", "");


        int Bnumber = int.Parse(Bday);



        int a1 = Bnumber, sum1 = 0, b1;


        while (a1 != 0)
        {
            b1 = a1 % 10;
            sum1 = sum1 + b1;
            a1 = a1 / 10;
        }


        txt_lucky.Text = sum1.ToString();

        if (sum1 < 10)
        {
            txt_lucky.Text = sum1.ToString();
        }

        int a2 = sum1, sum2 = 0, b2;

        if (sum1 > 9)
        {
            while (a2 != 0)
            {
                b2 = a2 % 10;
                sum2 = sum2 + b2;
                a2 = a2 / 10;
            }
            txt_lucky.Text = sum2.ToString();
        }

        int a3 = sum2, sum3 = 0, b3;
        if (sum2 > 9)
        {
            while (a3 != 0)
            {
                b3 = a3 % 10;
                sum3 = sum3 + b3;
                a3 = a3 / 10;
            }
            txt_lucky.Text = sum3.ToString();
        }


    }

1 个答案:

答案 0 :(得分:4)

这是递归的最佳选择,如果您使一个函数返回与输入相同类型的输出,则可以这样做。它会重复自己,直到以一位数字结尾。

public static string LuckyNumber(string date) // "06/07/1985"
{
  var result = (date ?? "")       // in case date is null
    .ToCharArray()                // ['0','6','/','0','7','/','1','9','8','5']
    .Where(char.IsNumber)         // ['0','6','0','7','1','9','8','5']
    .Select(char.GetNumericValue) // [0,6,0,7,1,9,8,5]
    .Sum()                        //  36
    .ToString();                  // "36"

  if (result.Length == 1) return result; //"36" is not 1 digit, so...
  return LuckyNumber(result);            //repeat the above with "36"
}

实施:

string date = "06/07/1985";
var luckyNumber = LuckyNumber(date);
System.Console.WriteLine(luckyNumber);

提琴: https://dotnetfiddle.net/5M7Ozv