判斷閏年
- 年份能夠要400整除.(2000)
- 年份能夠被4整除,但不能被100整除. (2008)
1
2
3
4
5
6
7
Console.WriteLine("**請輸入年份***");
int input = Convert.ToInt32(Console.ReadLine());
if ((input % 400 == 0) || (input % 4 == 0 && input % 100 != 0)) {
Console.WriteLine($"{input}是閏年");
}
Console.ReadKey();
練習: 輸入年份、月份,輸出該月份的天數。(要判斷閏年)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
//輸入年份、月份,輸出該月份的天數。(要判斷閏年)
try
{
Console.WriteLine("請輸入年份");
int year = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("請輸入月份");
try
{
int month = Convert.ToInt32(Console.ReadLine());
if (month >= 1 && month <= 12)
{
int day;
switch (month)
{
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
day = 31;
break;
case 2:
//2月有閏月、平月,所以要判斷當年是不是閏年
if (year % 400 == 0 || (year % 4 == 0 && year % 100 != 0)) {
day = 29; //閏年
} else {
day = 28; //平年
}
break;
default:
day = 30;
break;
}
Console.WriteLine($"{year}年{month}有{day}天");
} else //if月份不是1-12
{
Console.WriteLine("輸入的月份不符合要求,程式退出");
}
} catch //try月份
{
Console.WriteLine("輸入的月份有錯誤,程式退出");
}
} catch //try年份
{
Console.WriteLine("輸入的年份有錯誤,程式退出");
}