目的:
掌握基本的控制台输入输出操作。 学习使用DateTime处理日期。 练习使用if语句进行基础逻辑判断。 熟悉并实践使用switch语句。
作业内容:
编写一个C#控制台应用程序,实现以下功能: 提示用户以特定格式输入他们的出生年月日。 使用DateTime和TimeSpan计算用户从出生到当前的总天数。 使用switch语句根据用户的出生月份和当前月份计算用户的准确年龄。 关键代码提示:
代码实现
namespace 出生年月日计算
{
internal class Program
{
static void Main(string[] args)
{
Console.WriteLine("请输入您的出生年份(例如:1990):");
int birthYear = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("请输入您的出生月份(例如:7):");
int birthMonth = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("请输入您的出生日(例如:15):");
int birthDay = Convert.ToInt32(Console.ReadLine());
DateTime birthDate = new DateTime(birthYear, birthMonth, birthDay);
DateTime currentDate = DateTime.Now;
TimeSpan ageSpan = currentDate - birthDate;
int totalDays = ageSpan.Days;
Console.WriteLine($"您已经活了:{totalDays} 天");
// 计算年龄
int age = currentDate.Year - birthYear;
if (currentDate.Month < birthMonth || (currentDate.Month == birthMonth && currentDate.Day < birthDay))
{
age--;
}
Console.WriteLine($"您的年龄是:{age} 岁");
// 使用switch语句处理不同月份的天数计算
int daysInBirthMonth = 0;
switch (birthMonth)
{
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
daysInBirthMonth = 31;
break;
case 4:
case 6:
case 9:
case 11:
daysInBirthMonth = 30;
break;
case 2:
// 检查是否是闰年
daysInBirthMonth = (birthYear % 4 == 0 && (birthYear % 100 != 0 || birthYear % 400 == 0)) ? 29 : 28;
break;
default:
Console.WriteLine($"无效的出生月份。");
break;
}
// 判断出生当月是否已满月,如果没有,则减去相应的天数
if (currentDate.Month == birthMonth && currentDate.Day < birthDay)
{
totalDays -= daysInBirthMonth - birthDay + currentDate.Day;
}
Console.WriteLine($"考虑到您出生月份的天数,您实际上已经活了:{totalDays} 天。");
}
}
}