闰年计算 - 家庭作业

use*_*658 6 c++

#include <iostream>
using namespace std;

int main() {
    int what_year;

    cout << "Enter calendar year ";
    cin >> what_year;

    if (what_year - (n * 4) = 0 ) {

        cout << "leap year";
    }

    else
    {
        cout << "wont work";
    }

    system("Pause");
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

试图为类创建一个程序,找到一个闰年..不知道怎么问C++一个整数是否可以被一个整数整除?

Eri*_* J. 9

闰年规则是

 if year modulo 400 is 0 then
   is_leap_year
else if year modulo 100 is 0 then
   not_leap_year
else if year modulo 4 is 0 then
   is_leap_year
else
   not_leap_year
Run Code Online (Sandbox Code Playgroud)

http://en.wikipedia.org/wiki/Leap_year#Algorithm

您可以使用模运算符来查看一个数字是否可被另一个数字整除,即如果该除数中没有余数.

2000%400 = 0 //甚至可以被400整除

2001%400 = 1 //不能被400整除

有趣的是,几个着名的软件实现没有应用"400"部分,这导致2000年2月29日不存在这些系统.


Sin*_*rMJ 4

使用模函数。

if ((year % 4) == 0)
{
//leap year
}
Run Code Online (Sandbox Code Playgroud)

请注意,这并未考虑 100 年和 400 年的跳跃。

正确的代码是这样的

if(((year%4) == 0) && (((year%100)!=0) || ((year%400) == 0))
{
//leap year
}
Run Code Online (Sandbox Code Playgroud)