我需要找到最年长,最年轻的学生。最终用户必须将bday输入字符串。
DateTime young = DateTime.MinValue;
DateTime old = DateTime.MinValue;
foreach (var d in students)
{
try
{
DateTime dt = Convert.ToDateTime(d.dob);
int result = DateTime.Compare(young, dt);
if (result < 0)
{
old = dt;
}
if (result > 0)
{
young = dt;
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message.ToString());
}
}
Console.WriteLine("the youngest age is {0}",young);
Console.WriteLine("the oldest age is {0}", old);
逻辑有问题,我无法得到确切的输出。
答案 0 :(得分:4)
看一下这部分:
int result = DateTime.Compare(young, dt);
if (result < 0)
{
old = dt;
}
这看起来对你好吗?您是否真的要根据候选值是否早于最年轻的值来调整最旧的值?
此外:
DateTime
值的比较可以使代码更像更多。earliest
和latest
会比oldest
和youngest
更清晰;最年长的人是生日最早的人,但就日期而言,早晚更有意义young
和old
的初始值是相同的...想想这是否真的是你想要的。 (提示:你试图表示值的上限和下限。如果那些以相同的值开头,那你就麻烦了......)答案 1 :(得分:2)
你遗失了一些东西int result = DateTime.Compare(young, dt);
我觉得问题与错误分配有关...你需要检查年龄较小的
try
{
DateTime dt = Convert.ToDateTime(d.dob); // and what is dob ?
int result = DateTime.Compare(young, dt);
if (result < 0)
{
old = dt;
}
if (result > 0)
{
young = dt;
}
}
答案 2 :(得分:1)
您需要将dt与旧版本(如果较旧版本)进行比较,并将其与年轻版本(如果年龄较小)进行比较。
DateTime young = DateTime.MinValue;
DateTime old = DateTime.MaxValue;
foreach (var d in students)
{
DateTime dt = Convert.ToDateTime(d.dob);
old = old < dt ? old : dt;
young = young > dt ? young : dt;
}
Console.WriteLine("the youngest age is {0}", young);
Console.WriteLine("the oldest age is {0}", old);
答案 3 :(得分:0)
if ( dt < young )
{
young = dt;
}
if ( old < dt )
{
old = dt
}
答案 4 :(得分:0)
DateTime mv = dOb;
string oldname=sName;
string youngname=sName;
foreach (var mo in students)
{
int result = DateTime.Compare(mo.dob, mv);
if (result == -1)
{
mv = mo.dob;
oldname = mo.name;
}
if (result == 1)
{
mv = mo.dob;
youngname = mo.name;
}
}
Console.WriteLine("the youngest student is: {0}", youngname);
Console.WriteLine();
Console.WriteLine("the oldest student is: {0}", oldname);
Console.WriteLine();