-1

我需要找到年龄最大和最小的学生。最终用户必须将生日输入到字符串中。

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

逻辑有问题,我无法获得准确的输出。

4

5 回答 5

4

看看这部分:

int result = DateTime.Compare(young, dt);
if (result < 0)
{
    old = dt;
}

这对你来说是正确的吗?你真的应该根据候选值是否早于最年轻的值来调整最旧的值吗?

还:

  • 用于比较DateTime值的运算符重载可以使这样的代码简单。
  • 使用earliestand会比andlatest更清晰;最年长的人是生日最早的人,但就日期而言,早晚更有意义oldestyoungest
  • young和的初始值old是相同的……想想这是否真的是你想要的。(提示:您正在尝试表示值的上限和下限。如果它们以相同的值开始,那么您就有麻烦了......)
于 2012-07-20T07:22:40.363 回答
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;
    }
}
于 2012-07-20T07:28:55.633 回答
1

您需要将 dt 与 old (如果它较旧)进行比较,并将其与 young (如果它较年轻)进行比较。

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);
于 2012-07-20T07:26:51.890 回答
0

日期时间 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();
于 2012-07-30T11:19:52.823 回答
0
if ( dt < young )
{
   young = dt;
}

if ( old < dt )
{
   old = dt
}
于 2012-07-20T07:22:19.643 回答