[英]My program is too long. I want to shorten it using a loop method
I am trying to find a lucky number from my birthday, ex: 1985 June 07. My birthday lucky number 1+9+8+5+6+7=36 >> 3+6 = 9. My lucky number is 9. I tried to code. 我想从我的生日中找到一个幸运数字,例如:1985年6月7日。我的生日幸运数字1 + 9 + 8 + 5 + 6 + 7 = 36 >> 3 + 6 =9。我的幸运数字是9。我尝试编码。 I used while code 4 times.
我在编码时使用了4次。 I want to shorten it and I want to get the digit sum of any length number.
我想缩短它,我想获取任何长度数字的数字总和。 How to code it?
怎么编码呢?
c# 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();
}
}
This is a great candidate for recursion, which you can do if you make a function that returns the same type of output as its input. 这是递归的最佳选择,如果您使一个函数返回与输入相同类型的输出,则可以这样做。 It will repeat itself until it ends up with a one-digit number.
它将重复自身,直到以一位数字结尾。
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"
}
Implementation: 实现方式:
string date = "06/07/1985";
var luckyNumber = LuckyNumber(date);
System.Console.WriteLine(luckyNumber);
fiddle: https://dotnetfiddle.net/5M7Ozv 小提琴: https : //dotnetfiddle.net/5M7Ozv
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.