1. 程式人生 > >C語言 計算某年某月某日在該年的第幾天

C語言 計算某年某月某日在該年的第幾天

廢話不多說,上程式碼

通過傳入year,month,day來獲取天數

int getDay(int y, int m, int d) {
	int rtnDay = d;
	int day[] = { 31, 28, 31, 30, 31, 30, 31, 31,30, 31, 30 };
	int moon = !(y % 4) && y % 100 || !(y % 400);
	day[1] = 28 + moon;
	for (size_t i = 0; i < m - 1; i++) {
		rtnDay += day[i];
	}
	return rtnDay;
}

通過定義結構體返回天數
首先定義一個Date結構體

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

然後是結構體版的程式碼

int getDay(Date * d) {
	int rtnDay = d->day;
	int day[] = { 31, 28, 31, 30, 31, 30, 31, 31,30, 31, 30 };
	int moon = !(d->year % 4) && d->year % 100 || !(d->year % 400);
	day[
1] = 28 + moon; for (size_t i = 0; i < d->month - 1; i++) { rtnDay += day[i]; } return rtnDay; }

總程式碼

#include <stdio.h>

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

int getDay(Date * d);

int main() {
	Date d = { 2013, 3, 1 };
	printf("%d\n", getDay(&d));
return 0; } int getDay(Date * d) { int rtnDay = d->day; int day[] = { 31, 28, 31, 30, 31, 30, 31, 31,30, 31, 30 }; int moon = !(d->year % 4) && d->year % 100 || !(d->year % 400); day[1] = 28 + moon; for (size_t i = 0; i < d->month - 1; i++) { rtnDay += day[i]; } return rtnDay; }