c#练习_____出生年月日计算

目的:

        掌握基本的控制台输入输出操作。 学习使用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} 天。");
        }
    }
}

 

 

 

 

 

 

 

 

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值