如何找到闰年编程用C [英] How to find leap year programatically in C

查看:120
本文介绍了如何找到闰年编程用C的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我做了用C找到输入的年份是否为闰年的程序。但遗憾的是它不工作良好。它说,一年就是大跃进和preceding一年不是闰年。

 #包括LT&;&stdio.h中GT;
#包括LT&;&CONIO.H GT;
INT yearr(INT年);
无效的主要(无效)
{
    INT年;
    的printf(请输入年份:);
    scanf函数(%d个,&安培;一年);
    如果(!yearr(年))
    {
        的printf(这是一个闰年。);
    }
    其他
    {
    的printf(这是不是闰年);
    }
残培();
}
INT yearr(INT年)
{
    如果((年%4 == 0)及和放大器;!(年/ 4 = 0))
    返回1;
    其他
    返回0;
}

阅读评论后,我编辑我的编码为:

 #包括LT&;&stdio.h中GT;
#包括LT&;&CONIO.H GT;
INT yearr(INT年);
无效的主要(无效)
{
    INT年;
    的printf(请输入年份:);
    scanf函数(%d个,&安培;一年);
    如果(!yearr(年))
    {
        的printf(这是一个闰年。);
    }
    其他
    {
    的printf(这是不是闰年);
    }
残培();
}
INT yearr(INT年)
{
    如果((年%4 == 0)
    {
    如果(年%400 == 0)
    返回1;
    如果(每年100%== 0)
    返回0;
    }
    其他
    返回0;
}


解决方案

您的逻辑来确定一个闰年是错误的。这应该让你(维基百科)启动:

 如果一年400模数为0
       然后is_leap_year
否则,如果一年100模数为0
       然后not_leap_year
否则,如果一年模4为0
       然后is_leap_year
其他
       not_leap_year

X模是表示剩余 X 划分是。例如,12模5 2。

I made a program using C to find whether the entered year is a leap year or not. But unfortunately its not working well. It says a year is leap and the preceding year is not leap.

#include<stdio.h>
#include<conio.h>
int yearr(int year);
void main(void)
{
    int year;
    printf("Enter a year:");
    scanf("%d",&year);
    if(!yearr(year))
    {
        printf("It is a leap year.");
    }
    else
    {
    printf("It is not a leap year");
    }


getch();
}
int yearr(int year)
{
    if((year%4==0)&&(year/4!=0))
    return 1;
    else
    return 0;
}

After reading the comments i edited my coding as:

#include<stdio.h>
#include<conio.h>
int yearr(int year);
void main(void)
{
    int year;
    printf("Enter a year:");
    scanf("%d",&year);
    if(!yearr(year))
    {
        printf("It is a leap year.");
    }
    else
    {
    printf("It is not a leap year");
    }


getch();
}
int yearr(int year)
{
    if((year%4==0)
    {
    if(year%400==0)
    return 1;
    if(year%100==0)
    return 0; 
    }
    else
    return 0;
}

解决方案

Your logic to determine a leap year is wrong. This should get you started (from Wikipedia):

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

x modulo y means the remainder of x divided by y. For example, 12 modulo 5 is 2.

这篇关于如何找到闰年编程用C的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆