这是检查C ++中leap年的正确方法吗?

时间:2019-12-28 04:13:05

标签: c++ leap-year

在C ++中检查a年是否需要所有这些?

#include<iostream>
using namespace std;
int main(){
    int year;
    cout<<"Enter a year: ";
    cin>>year;
    if(((year%400==0) || (year%4==0))&&(year%100!=0))
        cout<<year<<" is leap year.";
    else
        cout<<"Not leap year.";
}

1 个答案:

答案 0 :(得分:0)

最好将表达式的怪异性拆分为一个单独的函数(并确实在该函数中的内单独进行检查),以使发生的事情更清晰,例如:

bool IsLeapYear(unsigned int year) {
    if ((year % 400) == 0) return true;  // multiple of 400, yes.
    if ((year % 100) == 0) return false; // else, multiple of 100, no.
    if ((year % 4) == 0)   return true;  // else, multiple of 4, yes.
                           return false; // else no.
}

实际上,通过(临时)安装测试工具来检查各种值的正确性(例如,一个完整的程序),您可以做得更好:

bool IsLeapYear(unsigned int year) {
    if ((year % 400) == 0) return true;  // multiple of 400, yes.
    if ((year % 100) == 0) return false; // else, multiple of 100, no.
    if ((year % 4) == 0)   return true;  // else, multiple of 4, yes.
                           return false; // else no.
}

#include <iostream>

void Chk(unsigned int year, bool expected) {
    if (IsLeapYear(year) != expected) {
        std::cout << year << " BAD, expected "
            << (expected ? "true" : "false") << '\n';
    } else {
        std::cout << year << " GOOD\n";
    }
}

void TestHarness() {
    Chk(1599, false); Chk(1600, true);  Chk(1601, false); Chk(1604, true);
    Chk(1699, false); Chk(1700, false); Chk(1701, false);
    Chk(1999, false); Chk(2000, true);  Chk(2001, false);
}

int main() {
    TestHarness(); // just comment out if not using.

    int year;
    std::cout << "Enter a year: ";
    std::cin >> year;

    if (IsLeapYear(year)) {
        std::cout << year << " is a leap year.\n";
    } else {
        std::cout << year << " is not a leap year.\n";
    }
}