switch case应用-输入年月日判断当年第几天

本文介绍了一个简单的Java程序,该程序通过用户输入的日期计算并输出这一年中的第几天。程序考虑了平年和闰年的不同,并使用switch-case语句进行月份到天数的转换。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

switch 的简单应用
  1. 熟练判断是否瑞年
  2. 熟练使用switch case 的语法
  3. 掌握switch case 的执行入口和break结束的位置
public class YearDays {
    public static void main(String[] args) {
        Scanner cin = new Scanner(System.in);
        int sum = 0;
        System.out.println("请输入年 月 日:\n");
        int year = cin.nextInt(), mouth = cin.nextInt(), day = cin.nextInt();
        System.out.println("您输入的年 月 日为:\n" + year + "  " + mouth + "  " + day
                + "  ");

        {
            switch (mouth)

            {
            case 12:
                sum += 30;
            case 11:
                sum += 31;
            case 10:
                sum += 30;
            case 9:
                sum += 31;
            case 8:
                sum += 31;
            case 7:
                sum += 30;
            case 6:
                sum += 31;
            case 5:
                sum += 30;
            case 4:
                sum += 31;
            case 3:
                sum += 28;
            case 2:
                sum += 31;
            case 1:
                sum += day;
                break;
            }
            if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0)
                if (mouth > 2)
                    sum += 1;
            System.out.println("是当年的第:" + sum + "天");
        }
    }
在C语言中,要判断给定的年、月、日是否为当月的第几天,你可以创建一个函数来处理这个计算。以下是一个简单的步骤: 1. 首要导入必要的头文件,如`stdio.h`用于输入,`time.h`用于获取当前日期作为参考。 ```c #include <stdio.h> #include <time.h> ``` 2. 创建一个辅助函数,例如 `days_in_month(int month, int year)` 来计算指定月有多少天。注意,闰年的二月有29天,其他非闰年2月只有28天。 ```c int days_in_month(int month, int year) { switch(month) { case 2: return (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)) ? 29 : 28; case 4: case 6: case 9: case 11: return 30; default: return 31; } } ``` 3. 主函数中接收用户输入并调用上面的函数: ```c int main() { int day, month, year; printf("请输入年份(yyyy): "); scanf("%d", &year); printf("请输入(mm): "); scanf("%d", &month); printf("请输入日期(dd): "); scanf("%d", &day); // 如果输入非法,可以添加错误检查 if(month < 1 || month > 12 || day < 1 || day > days_in_month(month, year)) { printf("输入的日期无效!\n"); return 1; } // 判断给定日期是不是当月的第几天 int position = day; // 初始化为给定的日期,然后更新到实际位置 time_t now = time(NULL); tm* current_time = localtime(&now); // 获取当前时间结构 // 从给定日期减去开始的天数,得到当月第一天的位置 for (current_time->tm_mday -= 1; current_time->tm_mday >= 1; current_time->tm_mday--) { if (current_time->tm_mon + 1 == month && current_time->tm_year + 1900 == year) { position++; break; } } printf("给定的日期 %d/%d/%d 是当年的第 %d 天.\n", month, day, year, position); return 0; } ```
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值