顾乔芝士网

持续更新的前后端开发技术栈

使用C#编程判断某一年是否为闰年

基于上传视频讲解,使用编程判断某一年是否为闰年的程序代码:

代码1:使用if语句(If...else...)

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace leapYear
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            ushort nyear;
            if(ushort.TryParse(textBox1.Text,out nyear))
            {
               if ((nyear % 4 == 0 && nyear % 100 != 0) || nyear % 400 == 0)
                {
                    textBox2.Text = textBox1.Text + "是闰年";
                }
                else
                {
                    textBox2.Text = textBox1.Text + "不是闰年";
                }               
            }
            else
            {
                MessageBox.Show("请输入正确年份");
            }
        }
    }
}

代码2:使用条件运算符(?:):条件运算符会根据布尔类型值或者布尔表达式返回冒号前后表达式中的一个,条件如果为true返回冒号前面的表达式,条件如果为false返回冒号后面的表达式:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace leapYear
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            ushort nyear;
            if(ushort.TryParse(textBox1.Text,out nyear))
            { 
              //使用条件运算符(?:)
                textBox2.Text=(nyear % 4 == 0 && nyear % 100 != 0) || nyear % 400 == 0 ? textBox1.Text + "是闰年" : textBox1.Text + "不是闰年";
            }
            else
            {
                MessageBox.Show("请输入正确年份");
            }
        }
    }
}
控制面板
您好,欢迎到访网站!
  查看权限
网站分类
最新留言