定義一個結構體變量(包括年、月、日)。計算該日在本年中是第幾天,注意閏年問題


定義一個結構體變量(包括年、月、日)。計算該日在本年中是第幾天,注意閏年問題

解題思路:

用一個日期數組保存每一月的天數,二月的天數記為28天,后面根據輸入的時間確定是否是閏年的二月,如果是,天數在加1。

#include <stdio.h>

struct Date{
	int year;
	int month;
	int day;
};

int main(){
	struct Date date;
	printf("Please give date: ");
	scanf("%d%d%d", &date.year, &date.month, &date.day);
	int Days[13] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
	
	int i, days = 0;
	for (i = 1; i < date.month; i++)
		days += Days[i];
	days += date.day;
    //如果包含閏年的二月,天數加1
    if(date.month > 2)
    {
       if (date.year%400 == 0 || (date.year%4 == 0 && date.year%100 != 0)){
            ++days;
		} 
    }
	printf("It's day %d in the year.\n", days);
	return 0;
}

運行截圖:

定義一個結構體變量(包括年、月、日)。計算該日在本年中是第幾天,注意閏年問題


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM