我需要在C中創建一個基本日期計算器,用戶輸入日期格式爲YYYY-MM-DD
。我有它的基礎知識。雖然我不需要,但我想要多花一點時間並考慮閏年。該程序運行良好;但是,它不能正確計算閏年。當我輸入日期2016-02-26
時,我應該得到2016-03-04
的預期結果,但我得到2016-03-03
的結果。我認爲,如果我使用模數的話,使用if else語句來實現以下效果。在C中創建日期計算器C
if (month == 2 && year % 4) days = 29;
else days = 28;
這裏是我完整的代碼...
//Does not require <stdlib.h>
#include <stdio.h>
// Set variables
int newDay, newMonth, newYear, daysInMonth, daysRemain;
// Set structure for day month year
struct date {
int day, month, year;
};
// set structure for date
struct date d1;
int main (void) {
//Intro
printf("Date calculation program by Keith A. Russell");
//Asks for user input
printf("\n\nPlease enter the year in four digit format (YYYY) ");
scanf("%i", &d1.year);
printf("\nEnter the month in two digit format (MM) ");
scanf("%i", &d1.month);
printf("\nEnter the day in two digit format (DD) ");
scanf("%i", &d1.day);
//Runs calculations to increase the date by a week
newDay = d1.day + 7;
newMonth = d1.month;
newYear = d1.year;
daysRemain = 0;
//For if the next week is going to be greater than the next month
if (newDay > 28)
checkMonth(); //Runs checkMonth Function
//Prints the dates
printf("\nThe new date is %i-%i-%i: \n", newYear, newMonth, newDay);
}
checkMonth() {
if (d1.month == 1 || 3 || 5 || 7 || 8 || 10 || 12)
daysInMonth = 31; //For months with 31 days
if (d1.month == 2 && d1.year % 4) //Attempt to calculate leap year
daysInMonth = 29;
else {
daysInMonth = 28; //All other years
}
if (d1.month == 4 || 6 || 9 || 11) //For months with 30 days
daysInMonth = 30;
//Sets up to advance the year if approaching the end of year
if (newDay > daysInMonth) {
daysRemain = newDay - daysInMonth;
newDay = daysRemain;
newMonth++;
checkYear();
}
}
//Runs function to advance to the next year
checkYear() {
if (d1.month == 12)
if (daysRemain > 0) {
newYear++;
newMonth = 1;
}
}
如果有計算閏年和它包括在該計劃的更優雅的方式,我很感激很大。謝謝。
請注意,您的閏年的計算是草率的。在1901年至2019年範圍內可以使用多年;它在1900年和2100年都沒有通過(這兩次都不是閏年)。如果年份可以被400整除,那就是閏年;否則,如果年可以被100整除,那不是閏年;否則,如果年可以被4整除,那麼這是一個閏年;否則,它不是。這不是計算結果的最佳順序;但是,這是爲了給規則。 –
@JonathanLeffler:閏年計算實際上已經完全被破壞:它只能產生1700,1800,1900,2100的正確結果... – chqrlie
@chqrlie:Urg!看起來你是對的 - 我沒有注意到這種情況的隱含倒置。那麼,我淪落爲藉口「我認識到有一個問題」和「我認爲我診斷出了正確的算法」。由於公曆日曆的洛可可(如果不是巴洛克式的)性質,日曆計算顯得非常令人滿意。 –