本月天数

//
//  main.cpp
//  project
//
//  Created by 徐伟 on 6/8/16.
//  Copyright © 2016 fizz_i. All rights reserved.
//


#include<iostream>
using namespace std;
int main()
{
    int  year, month, days;
    cout << "请输入年、月: ";
    cin >> year >> month;
    switch(month)
    {
        case 1:
        case 3:
        case 5:
        case 7:
        case 8:
        case 10:
        case 12:
            days = 31;
            break;
        case 4:
        case 6:
        case 9:
        case 11:
            days = 30;
            break;
        case 2:
            if(year%4==0 && year%100!=0 ||year%400==0)
                days = 29;
            else
                days =28;
    }
    cout<<year<<"年"<<month<<"月共有"<<days<<"天。"<<endl;
    return 0;  
}

在 C 语言中计算本月天数,需要考虑不同月份的天数差异,以及二月在闰年和平年的不同天数。一年有 12 个月,其中一、三、五、七、八、十、十二月各有 31 天,四、六、九、十一月各有 30 天。二月比较特殊,闰年的二月有 29 天,平年的二月有 28 天,要确定二月的天数,就要先判断当年是否为闰年。 以下是几种实现方法: #### 方法一:使用 `switch` 语句 ```c #include <stdio.h> // 判断是否为闰年 int isLeapYear(int year) { return ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)); } // 计算本月天数 int daysInMonth(int year, int month) { int days; switch (month) { case 1: case 3: case 5: case 7: case 8: case 10: case 12: days = 31; break; case 4: case 6: case 9: case 11: days = 30; break; case 2: days = isLeapYear(year) ? 29 : 28; break; default: days = 0; // 无效月份 break; } return days; } int main() { int year, month; printf("请输入年份和月份(用空格分隔): "); scanf("%d %d", &year, &month); int days = daysInMonth(year, month); if (days == 0) { printf("输入的月份无效。\n"); } else { printf("%d 年 %d 月有 %d 天。\n", year, month, days); } return 0; } ``` #### 方法二:使用数组 ```c #include <stdio.h> // 判断是否为闰年 int isLeapYear(int year) { return ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)); } // 计算本月天数 int daysInMonth(int year, int month) { int pin[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; int run[] = {31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; if (isLeapYear(year)) { return run[month - 1]; } else { return pin[month - 1]; } } int main() { int year, month; printf("请输入年份和月份(用空格分隔): "); scanf("%d %d", &year, &month); if (month < 1 || month > 12) { printf("输入的月份无效。\n"); } else { int days = daysInMonth(year, month); printf("%d 年 %d 月有 %d 天。\n", year, month, days); } return 0; } ```
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值