例如70105-计算符合参数年龄范围的任何出生日期
CalculateDob(int youngestAge, int oldestAge)
{
Random r = new Random();
int age = 0;
age = r.Next(70, 105);
var year = DateTime.Now.Year - age;
var month = r.Next(1, 12);
var day = r.Next(1, 28);
return new DateTime(year, month, day);
}
我当前的解决方案几乎可以工作,但是在某些极端情况下会失败,即在某些情况下由于我认为是一个月的问题而返回69。
有什么建议吗?
答案 0 :(得分:0)
您之所以会达到69岁,是因为如果CalculateDob
返回的月份是当前月份(DateTime.Now)
之后的月份;到那时Dob仍达不到70年。另外,您应该从方法中带出随机构造函数,并将其设为静态,以免在每次调用时都保持rand生成器的种子状态。
public static void Main(string[] args)
{
for (int i = 0; i < 100; i++)
{
var birthDate = CalculateDob(70, 105);
var now = DateTime.Now;
int age = now.Year - birthDate.Year;
if (now.Month < birthDate.Month || (now.Month == birthDate.Month && now.Day < birthDate.Day))
{
age--;
}
Console.WriteLine(age);
}
}
//Construct this as static so that we don't keep seeding the rand
private static readonly Random _random = new Random();
static DateTime CalculateDob(int youngestAge, int oldestAge)
{
int age = 0;
age = _random.Next(70, 105);
var today = DateTime.Now;
var year = today.Year - age;
var month = _random.Next(1, 12);
//Age might less than youngest age,
//if born at/after current month, edge condition
if (month >= today.Month)
{
month = today.Month - 1;
if (month < 1)
{
year--;
month = 12;
}
}
var day = _random.Next(1, DateTime.DaysInMonth(year, month));
return new DateTime(year, month, day);
}