• 欢迎访问开心洋葱网站,在线教程,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站,欢迎加入开心洋葱 QQ群
  • 为方便开心洋葱网用户,开心洋葱官网已经开启复制功能!
  • 欢迎访问开心洋葱网站,手机也能访问哦~欢迎加入开心洋葱多维思维学习平台 QQ群
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏开心洋葱吧~~~~~~~~~~~~~!
  • 由于近期流量激增,小站的ECS没能经的起亲们的访问,本站依然没有盈利,如果各位看如果觉着文字不错,还请看官给小站打个赏~~~~~~~~~~~~~!

Go语言计算指定年月的天数

go 水墨上仙 1632次浏览

Go语言计算指定年月天数

package main
import (
	"fmt"
	"bufio"
	"os"
	"regexp"
	"strconv"
)
func main() {
	year := input("year", "^[0-9]{1}[0-9]{3}$")
	month := input("month", "^(0{1}[0-9]{1}|1{1}[0-2]{1})$")
	count(year, month)
	fmt.Println("Press Enter button to continue ...")
	reader := bufio.NewReader(os.Stdin)
	lastInput, _, err := reader.ReadRune()
	if err != nil {
		fmt.Fprintln(os.Stderr, "Occur error when input (last) '", lastInput, "':", err)
	}
	return
}
func count(year int, month int) (days int) {
	if month != 2 {
		if month == 4 || month == 6 || month == 9 || month == 11 {
			days = 30
		} else {
			days = 31
			fmt.Fprintln(os.Stdout, "The month has 31 days");
		}
	} else {
		if (((year % 4) == 0 && (year % 100) != 0) || (year % 400) == 0) {
			days = 29
        } else {
			days = 28
        }
	}
	fmt.Fprintf(os.Stdout, "The %d-%d has %d days.\n", year, month, days)
	return
}
func input(name string, regexpText string) (number int) {
	var validNumber = false
	for !validNumber {
		fmt.Println("Please input a", name, ": ")
		reader := bufio.NewReader(os.Stdin)
		inputBytes, _, err := reader.ReadLine()
		if err != nil {
			fmt.Fprintln(os.Stderr, "Occur error when input", name, ":", err)
			continue
		}
		inputText := string(inputBytes)
		validNumber, err = regexp.MatchString(regexpText, inputText)
		if err != nil {
			fmt.Fprintln(os.Stderr, "Occur error when match", name, "(", inputText, "):",err)
			continue
		}
		if validNumber {
			number, err = strconv.Atoi(inputText)
			if err != nil {
				fmt.Fprintln(os.Stderr, "Occur error when convert", name, "(", inputText, "):", err)
				continue
			}
		} else {
			fmt.Fprintln(os.Stdout, "The", name, "(", inputText, ") does not have the correct format!")
		}
	}
	fmt.Println("The input", name, ": ", number)
	return
}

 


开心洋葱 , 版权所有丨如未注明 , 均为原创丨未经授权请勿修改 , 转载请注明Go语言计算指定年月的天数
喜欢 (0)
加载中……