gpt4 book ai didi

c# - 我的程序太长了。我想用循环方法缩短它

转载 作者:太空宇宙 更新时间:2023-11-03 20:50:38 25 4
gpt4 key购买 nike

我想从我的生日中找到一个幸运数字,例如: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();
}


}

最佳答案

这是递归的一个很好的候选者,如果你创建一个返回与其输入相同类型的输出的函数,你就可以这样做。它会不断重复,直到以一位数字结尾。

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);

fiddle : https://dotnetfiddle.net/5M7Ozv

关于c# - 我的程序太长了。我想用循环方法缩短它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55779076/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com