检查C程序,如果输入的日期是否有效 [英] A C program to check if the entered date is valid or not

查看:117
本文介绍了检查C程序,如果输入的日期是否有效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我被要求权的方案用来检查用户输入的日期是合法的或者不C.我试着写,但我猜的逻辑是不对的。

I was asked to right a program which checks if the date entered by the user is legitimate or not in C. I tried writing it but I guess the logic isn't right.

//Legitimate date
#include <stdio.h>
void main()
{
    int d,m,y,leap;
    int legit = 0;
    printf("Enter the date\n");
    scanf("%i.%i.%i",&d,&m,&y);
    if(y % 400 == 0 || (y % 100 != 0 && y % 4 == 0))
        {leap=1;}
    if (m<13)
    {
        if (m == 1 || (3 || ( 5 || ( 7 || ( 8 || ( 10 || ( 12 )))))))
            {if (d <=31)
                {legit=1;}}
        else if (m == 4 || ( 6 || ( 9 || ( 11 ) ) ) )
            {if (d <= 30)
                {legit = 1;}}
        else
            {
                        if (leap == 1)
                              {if (d <= 29)
                                    {legit = 1;}}
                        if (leap == 0)
                              {{if (d <= 28)
                                    legit = 1;}}
             }
    }
    if (legit==1)
        printf("It is a legitimate date!\n");
    else
        printf("It's not a legitimate date!");

}

我得到正确的输出,如果一个月有31天,但在几个月的休息,输出是合理的,只要一天是小于32你的帮助是AP preciated!

I am getting the correct output if the month has 31 days but for the rest of the months, the output is legitimate if the day is less than 32. Your help is appreciated!

推荐答案

您不能链条件语句是这样的:

You can't chain conditionals like this:

if (m == 1 || (3 || ( 5 || ( 7 || ( 8 || ( 10 || ( 12 )))))))

相反,你将不得不专门测试场景:

Instead, you'll have to test each scenario specially:

if (m == 1 || m == 3 || m == 5 || ...)

您只需版本的手术室首次测试的结果(米== 1 )使用 3 的价值,这在C为非零,因此总是一个true

Your version simply ORs the results of the first test (m == 1) with the value of 3, which in C is a non-zero and therefore always a boolean true.

这篇关于检查C程序,如果输入的日期是否有效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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