我怎样才能让这个程序正确计算我的年龄?(可能很简单,我是初学者)

  • 本文关键字:简单 初学者 计算 程序 c#
  • 更新时间 :
  • 英文 :


我正在编写一个计算您的年龄的小控制台程序,稍后我会添加一些其他内容,但问题是此代码没有正确计算年龄,它只是减去了实际年份 - 出生年份,但是如果您没有过生日,它显示的年龄错误,我怎么能在我拥有的所有日子和月份中计算此总和?我尝试了很多东西,但没有奏效:(

有没有办法使用 if 语句来做到这一点?

using System;
using System.Collections.Generic;
using System.Text;
namespace para_joel
{
public class Person
{
public string name;
public string surname;
public int birthDay;
public int birthMonth;
public int birthYear;
public int Age()
{
int actualYear = DateTime.Now.Year;
int actualMonth = DateTime.Now.Month;
int actualDay = DateTime.Now.Day;
return actualYear - birthYear;
}
}
}

您需要将三个 int 属性从 Person 转换为 Datetime,如下所示:

DateTime birthday = new DateTime(birthYear, birthMonth, birthDay);

然后你需要将今天的日期转换为日期时间(不是我怎么做,而是使用你的变量(:

DateTime today = new DateTime(actualYear, actualMonth, actualDay);

然后你需要减去这两个:

var age = today - birthday;

这将返回天数,因此您需要除以 365 以获得年龄,一旦您走得那么远,您就可以根据需要进行四舍五入。

最新更新