go 用switch语句实现输入某年某月某日,判断这一天是这一年的第几天
时间: 2024-10-20 20:03:17 浏览: 32
Go语言中,你可以使用`switch`语句结合简单的数学计算来实现这个功能。首先,你需要获取当前年份、月份和日期,然后根据不同月份的天数差异来判断。以下是一个基本的例子:
```go
package main
import "fmt"
func daysInMonth(year int, month int) int {
switch month {
case 1, 3, 5, 7, 8, 10, 12:
return 31
case 4, 6, 9, 11:
return 30
// 特殊情况,闰年二月有29天
case 2:
if isLeapYear(year) {
return 29
} else {
return 28
}
default:
fmt.Println("无效的月份")
return -1
}
}
// 判断是否为闰年
func isLeapYear(year int) bool {
if year % 4 != 0 {
return false
}
if year % 100 != 0 {
return true
}
if year % 400 != 0 {
return false
}
return true
}
func main() {
var input string
fmt.Print("请输入年份(YYYY)、月份(MM)和日期(DD): ")
_, monthStr, dayStr := input.Split(" ")
year, _ := strconv.Atoi(monthStr[0:4])
month, _ := strconv.Atoi(monthStr[4:])
day, _ := strconv.Atoi(dayStr)
if day <= 0 || day > daysInMonth(year, month) {
fmt.Printf("%d/%02d/%d 不是有效的一天", year, month, day)
} else {
fmt.Printf("%d/%02d/%d 是当年的第%d天", year, month, day, day)
}
}
//
阅读全文