Switch Case判断闰年练习

本文介绍了一个简单的C#程序,用于判断指定年份和月份的天数,并考虑了平年与闰年的区别。通过用户输入年份和月份,程序能够准确返回该月的总天数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  • 1 3 5 7 8 10 12的代码相同,只要写12月份就可以了
  • 精简代码,30天的可以放在default里面写
  • 可以把Console.WriteLine(“{0}年{1}月有{2}天”, year, month, day);放在Switch外面写
  • 当用户输入格式不正确的时候可能会报异常,使用try catch 解决。
  • if else 用来保证月份的值输入正确性
  • 注意try结束的位置
using System;

namespace 判断闰年
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("请输入一个年份:");
            try
            {
                int year= Convert.ToInt32(Console.ReadLine());
           

           
            Console.WriteLine("请输入一个月份:");
                try
                {

               
            int month = Convert.ToInt32(Console.ReadLine());
                    if(month>=1&&month<=12)
                    {

                    
            int day = 0;
            //1 3  5 7 8 10 12的代码相同,只要写12月份就可以了
            //精简代码,30天的可以放在default里面写
            //可以把Console.WriteLine("{0}年{1}月有{2}天", year, month, day);放在Switch外面写
            //当用户输入格式不正确的时候可能会报异常,使用try catch 解决。
            //if else 用来保证月份的值输入正确性
            switch (month)
            {
                case 1:
                case 3:
                case 5:
                case 7:
                case 8:
               
                case 10:
                case 12:
                    day = 31;
                   // Console.WriteLine("{0}年{1}月有{2}天", year, month, day);
                    break;
             
                case 2:
                    if(year%400==0||(year%4==0&&year%100!=0))
                    {
                        day = 29;
                    }
                   else
                    {
                        day = 28;
                    }
                   // Console.WriteLine("{0}年{1}月有{2}天", year, month, day);
                    break;
                default:day = 30;
                   // Console.WriteLine("{0}年{1}月有{2}天", year, month, day);
                    break;


            }
                    Console.WriteLine("{0}年{1}月有{2}天", year, month, day);
                    }
                    else
                    {
                        Console.WriteLine("月份在1-12之间,输入有误,程序退出");
                    }
                }//tr月份

                catch
                {
                    Console.WriteLine("月份输入有误,程序退出");
                }
            }//try 年份
            catch//年份
            {
                Console.WriteLine("年份输入有误,程序退出");
            }
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值