C++入门经典-例3.25-使用循环输出闰年

C++入门经典-例3.25-使用循环输出闰年

1:代码如下:

// 3.25.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <iostream>
using namespace std;

int main(int argc, _TCHAR* argv[])
{
//若直接使用for循环遍历1773-2012年,则需要执行240次判断。

    int year; //1773开始的第一个闰年
    int yearStart = 1773;//代表从何年开始
    int yearTo = 2012;//代表从何年结束
    
//其实可以将以下for循环条件设定为i<4,不过有些年份在世纪末,设定为i<8则是考虑到了这一点。
    for(int i = 0;i<8;i++ )  
    {
        if( (yearStart+i)%4==0 && (yearStart+i)%100!=0 || (yearStart+i)%400==0)
        {
            year = yearStart+i;  //此时year为1773开始的第一个闰年
            break;
        }
    }
    int count = 1;  //闰年个数
    
  for(int yearIter =year;yearIter<yearTo;count++)
    {
        
        
        if(yearIter%100 == 0&&yearIter%400 != 0)
        {
            yearIter+=4;//每隔4年判断一次
            count--;
            continue;
        }
        
        cout<<yearIter<<" ";
        if(count%10 == 0)
        {
            cout<<endl; //每10个年份换行
        } 
        yearIter+=4;
    }
 cout<<endl;
  //整个程序执行了共62次循环
    return 0;
}

View Code

运行结果:

posted @ 2017-09-14 09:11 一串字符串 阅读(...) 评论(...) 编辑 收藏

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值