You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#如何实现询问用户生日并计算已存活天数,修复代码运行问题

问题原因
  • 你拼接的出生日期字符串没有分隔符,DateTime.Parse无法识别这种无分隔的连续数字字符串,比如输入月份1、日期5、年份2000,拼接后得到的是152000,不符合任何标准日期格式,会直接抛出格式异常
  • 没有对用户输入做合法性校验,用户如果输入非数字内容、或者日期超出合法范围(比如月份输13、日期输32),也会触发运行错误
修复方案

对初学者更友好的方式是先将输入的年、月、日转为整数,直接调用DateTime的构造函数创建日期对象,不需要处理复杂的字符串格式适配,还可以加简单的输入校验避免非法输入导致崩溃。

修复后的完整代码如下:

Console.WriteLine("Hey, what's your name?");
Console.Write("Enter your name: ");
string YourName = Console.ReadLine();
Console.WriteLine("Wow what a nice name!");
Console.ReadLine();

Console.WriteLine("What about your age?");
int birthYear, birthMonth, birthDay;

// 出生年份校验
Console.Write("Enter your year of birth: ");
while (!int.TryParse(Console.ReadLine(), out birthYear) || birthYear < 1900 || birthYear > DateTime.Now.Year)
{
    Console.Write("输入不合法,请重新输入出生年份:");
}

// 出生月份校验
Console.Write("Enter your month of birth (number not actual month): ");
while (!int.TryParse(Console.ReadLine(), out birthMonth) || birthMonth < 1 || birthMonth > 12)
{
    Console.Write("输入不合法,请重新输入1-12之间的月份:");
}

// 出生日期校验,自动适配对应月份的合法天数
int maxDay = DateTime.DaysInMonth(birthYear, birthMonth);
Console.Write("Enter your day of birth: ");
while (!int.TryParse(Console.ReadLine(), out birthDay) || birthDay < 1 || birthDay > maxDay)
{
    Console.Write($"输入不合法,请重新输入1-{maxDay}之间的日期:");
}

DateTime myBirthDate = new DateTime(birthYear, birthMonth, birthDay);
TimeSpan myAge = DateTime.Now.Subtract(myBirthDate);
Console.WriteLine($"你已经存活了{myAge.TotalDays:F0}天");
Console.ReadLine();

如果你坚持想用字符串拼接+DateTime.Parse的写法,只需要给拼接的字符串加标准分隔符即可,修改对应行代码为:

DateTime myBirthAge = DateTime.Parse($"{BirthYear}-{BirthMonth}-{BirthDate}");

但这种写法没有输入校验,遇到非法输入依然会运行报错。

内容的提问来源于stack exchange,提问作者T-T

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 13:06:04