C# 我如何从01到99生成5个随机数并给出今天的';第六个号码是什么日期?
我需要创建一个6位数字,其中5位将从1到99中提取,第六位将是今天的日期(只有一天,而不是一个月),并将其放在label1中。我是初学者,所以很抱歉。命令式解决方案:C# 我如何从01到99生成5个随机数并给出今天的';第六个号码是什么日期?,c#,.net,windows-forms-designer,C#,.net,Windows Forms Designer,我需要创建一个6位数字,其中5位将从1到99中提取,第六位将是今天的日期(只有一天,而不是一个月),并将其放在label1中。我是初学者,所以很抱歉。命令式解决方案: var r = new Random(); var text = DateTime.Now.Day.ToString(); while (text.Length < 6) { // identify the next random prefix string between 1
var r = new Random();
var text = DateTime.Now.Day.ToString();
while (text.Length < 6)
{
// identify the next random prefix string between 1 and 99 inclusive
var prefix = (r.Next(99) + 1).ToString();
// reduce the prefix to the first character (1-9) if it would exceed the target total of 6
if (prefix.Length + text.Length > 6)
{
prefix = prefix.Substring(0, 1);
}
text = prefix + text;
}
label1.Text = text;
后者假设您可以访问类似于以下内容的生成器功能:
public static IEnumerable<T> Generate<T>(T start, Func<T, T> step)
{
var current = start;
while (true)
{
yield return current;
current = step(current);
}
}
公共静态IEnumerable生成(T开始,函数步骤)
{
无功电流=启动;
while(true)
{
产生回流电流;
电流=阶跃(电流);
}
}
如果一天有两位数怎么办?哦,是的,我没想过。如果可能的话,这样做可以删除5个数字或将其替换为日期。将第5个数字替换为日期创建Random
类的实例,使用Random.Next
从中创建4或5个数字(取决于当前日期是否>=10)并附加日期。如果要将其用作日期,考虑每年从0到99创建一个数字(或者整个HOG,使用一个像1950-2050的范围),然后以1-12的范围作为月份,然后玩一天。但是,请记住,月份可以有28天、29天、30天或31天(29天的规则很复杂(例如,1900年不是闰年))。此解决方案假设OP详细信息中规定的1-99天,而不是主题标题中规定的01-99天
public static IEnumerable<T> Generate<T>(T start, Func<T, T> step)
{
var current = start;
while (true)
{
yield return current;
current = step(current);
}
}