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  一串字符串  阅读(562)  评论(0编辑  收藏  举报