0
我應該接受用戶的輸入並說出它是否是有效的日期,但是有些日期打印出有效或無效,然後其他時間只需要輸入並且程序以無輸出結束。我的函數有什麼問題,某些數字集可以工作,而其他的則不行?
當用戶輸入15/11/11時,它重新排列到11/15/15。如果用戶輸入 12/12/12
,它可以正常工作,但04/16/16
只是不提供任何輸出。
我的函數中的問題在哪裏引起這個問題?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
//Declares function
int check_date(int month, int day, int year);
int main(void) {
int day, month, year;
//Asks user for input.
printf("Enter a date in this format : MM/DD/YY:");
//If user enters a wrong format it will be invalid.
if (scanf_s("%d/%d/%d", &month, &day, &year) == 3) {
check_date(day, month, year);
}
else {
printf("You entered a invalid date.\n");
}
system("pause");
return 0;
}
int check_date(int month, int day, int year) {
// If user inputs a valid date this will run.
if (month > 0 && month <= 12 && day > 0 && day <= 31 && year > 0 && year <= 99)
{
switch (month) {
//If users month input is 2(febuary) this case will run.
case 2:
//If it is a leap year and the day 29 is entered it is invalid.
if (year % 4 == 0) {
if (day == 29) {
printf("Invalid date.");
}
else {
printf("You entered a valid date, %d/%d/%d", month, day, year);
}
break;
//If user inputs 4 this case will run.
case 4:
//There is not 31 days in this month.
if (day == 31) {
printf("Invalid date.");
}
else {
printf("You entered a valid date, %d/%d/%d", month, day, year);
}
break;
//If user inputs 4 this case will run.
case 6:
//There is not 31 days in this month.
if (day == 31) {
printf("Invalid date.");
}
else {
printf("You entered a valid date, %d/%d/%d", month, day, year);
}
break;
//If user inputs 4 this case will run.
case 9:
//There is not 31 days in this month.
if (day == 31) {
printf("Invalid date.");
}
else {
printf("You entered a valid date, %d/%d/%d", month, day, year);
}
break;
//If user inputs 4 this case will run.
case 11:
//There is not 31 days in this month.
if (day == 31) {
printf("Invalid date.");
}
else {
printf("You entered a valid date, %d/%d/%d", month, day, year);
}
break;
//If user enters any other date other then the cases it is valid.
default:
printf("You entered a valid date, %d/%d/%d", month, day, year);
break;
}
//If user enters anything other then the correct format, this else will run.
else {
printf("You entered a invalid date.");
}
}
}
}
可追溯工作,其歷史可以沒有?請告訴我們您的輸入值,您可以確定這一點。 –
請使用[代碼格式化程序](http://codebeautify.org/c-formatter-beautifier) - 您忘記關閉一個開括號,並以'switch(..)else {INVALID; }'這在語法上是有效的,但不是你的意思 - 我投票結束,因爲這是一個錯字/格式問題。 –
然後你用'check_date(day,month,year)'調用函數,錯誤的順序。 –