蓝桥杯算法基础_星系炸弹_课程笔记

题目

在X星系的广袤空间中漂浮着许多X星人造“炸弹”,用来作为宇宙中的路标。
每个炸弹都可以设定多少天之后爆炸。
比如:阿尔法炸弹2015年1月1日放置,定时为15天,则它在2015年1月16日爆炸。
有一个贝塔炸弹,2014年11月9日放置,定时为1000天,请你计算它爆炸的准确日期。

以下程序实现了这一功能,请你填补空白处内容:

提示: json
先判断是否为闰年,这会影响2月份是28还是29,如果是闰年,2月份是29,如果不是,就是28

#include <stdio.h>

int main()
{
    int monthDays[12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
    int days = 1000;
    int year = 2014, month = 11, day = 9;
    int i;

    for (i = 0; i < days; i++)
    {
        day++;
        if (day > monthDays[month - 1])
        {
            day = 1;
            month++;
            if (month > 12)
            {
                month = 1;
                year++;
                ____________________;
            }
        }
    }

    printf("%d-%d-%d\n", year, month, day);

    getchar();
    return 0;
}
  • 空白处代码为:
if ((year % 400 == 0) || (year % 4 == 0 && year % 100 != 0))
    monthDays[1] = 29;
else
    monthDays[1] = 28;

问题分析

解题关键在于闰年判断:年份能被4整除且不能被100整除(普通闰年) or 年份能被400整除则为闰年(世纪闰年),闰年的2月有29天,平年只有28天

代码实现

#include<iostream>
using namespace std;

void CalculateBoomDate()
{
	int mouthdays[12] = { 31,28,31,30,31,30,31,31,30,31,30,31 }; //2014年不是闰年,因此此年的二月份为28天
	int days = 1000;
	int year = 2014; 
	int mouth = 11;
	int day = 9;
	for (int i = 0;i < days;i++)
	{
		day++;
		if (day > mouthdays[mouth - 1]) //对天数进行判断,看是否超过了当月的天数
		{
			day = 1;
			mouth++;
		}
		if (mouth > 12) //对月份进行判断,看是否超过了12,超过了月份就要重置,年份加一
		{
			mouth = 1;
			year++;
		}
		if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) //对年份进行判断,看是否为闰年,如果湿润年则2月有29天,需要对mouthdays这个数组进行改变
		{
			mouthdays[1] = 29;
		}
		else
		{
			mouthdays[1] = 28;
		}
	}
	cout << "炸弹爆炸的日期为:" << endl;
	cout << year << "年" << mouth << "月" << day << "日" << endl;
}

int main()
{
	CalculateBoomDate();

	system("pause");
	return 0;
}
  • 输出结果
炸弹爆炸的日期为:
201785日
请按任意键继续. . .
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值