Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.4k views
in Technique[技术] by (71.8m points)

python使用布尔值判断闰年出错

代码如下:

def is_leap(year):
    leap = False
    if year % 4 == 0:
        leap = True
        if year % 100 == 0 and year % 400 != 0:
        leap = False
    return leap


is_leap(7)
is_leap(12)
is_leap(100)
is_leap(400)

运行结果如下:
False
True
False
True

第二次将 leap 初始值设定为 True

def is_leap(year):
    leap = True
    if year % 4 == 0:
        leap = True
        if year % 100 == 0 and year % 400 != 0:
        leap = False
    return leap


is_leap(7)
is_leap(12)
is_leap(100)
is_leap(400)

运行结果如下,结果第一个变成了 True
True
True
False
True

这是怎么回事?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

判断任意年份是否为闰年,需要满足以下条件中的任意一个:
① 该年份能被 4 整除同时不能被 100 整除;
② 该年份能被400整除。

include <stdio.h>

int main()
{

int year,a;
printf("请输人年份:n");
scanf("%d",&year);
if(year%400==0)
    a=1;
else
{
    if(year%4==0&&year%100!=0)
        a=1;
    else
        a=0;
}
if(a==1)
{
    printf("%d 此年是闰年n",year);
}
else
{
    printf("%d 此年非闰年n",year);
}
return 0;

}


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...