我被要求纠正一个程序,该程序检查用户输入的日期是否合法在C中.我尝试写它但我猜逻辑是不正确的.
//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!");
}
Run Code Online (Sandbox Code Playgroud)
如果月份有31天,我会得到正确的输出,但在剩下的几个月中,如果当天小于32,则输出是合法的.我们的帮助表示赞赏!
我重写你的程序简单易行,我认为这可能会有所帮助
//Legitimate date
#include <stdio.h>
void main()
{
int d,m,y;
int daysinmonth[12]={31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}
int legit = 0;
printf("Enter the date\n");
scanf("%i.%i.%i",&d,&m,&y);
// leap year checking, if ok add 29 days to february
if(y % 400 == 0 || (y % 100 != 0 && y % 4 == 0))
daysinmonth[1]=29;
// days in month checking
if (m<13)
{
if( d <= daysinmonth[m-1] )
legit=1;
}
if (legit==1)
printf("It is a legitimate date!\n");
else
printf("It's not a legitimate date!");
}
Run Code Online (Sandbox Code Playgroud)