04-输入年月日,判断是今年的第几天


大致的思路是这样的,就是把输入的月份之前的月份天数加起来,在加上输入的月份的日数。

比如:3月2日,就是1、2月份的天数加起来,再加上2

还有一点就是平年和闰年2月份的天数是不同的。这里要进行平闰年的判断。



以下的代码是用Java写的:总之,是一个for循环整体计算月的总天数的。

import java.util.Scanner;

public class Test {
	public static void main(String[] args) {
		// 定义变量,分别保存用户输入的年月日变量
		int year, month, day;
		// 定义一个变量,用来保存这是该年的第几天
		int total = 0;
		// 获得用户输入的年月日
		Scanner scanner = new Scanner(System.in);
		System.out.println("请输入一个年份吧:");
		year = scanner.nextInt();
		System.out.println("请输入一个月份吧:");
		month = scanner.nextInt();
		System.out.println("请输入一个日吧:");
		day = scanner.nextInt();

		// 判断是平年还是闰年
		for (int foremonth = 1; foremonth < month; foremonth++) {
			switch (foremonth) {
			case 1:
			case 3:
			case 5:
			case 7:
			case 8:
			case 10:
			case 12:
				total += 31;
				break;
			case 4:
			case 6:
			case 9:
			case 11:
				total += 30;
				break;
			}
			// 闰年,二月份为29天
			if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) {
				if (foremonth == 2) {
					total += 29;
				}
			} else {
				// 如果是平年,二月份为28天
				if (foremonth == 2) {
					total += 28;
				}
			}
		}

		// 加上这个月的天数
		total = total + day;
		System.out.println("今天是今天第:" + total + "天");
	}
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

会编程的阿强

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值