定義一個結構體類型表示日期(年、月、日)。main中輸入一個日期,計算該日期是當年的第幾天。

定義一個結構體類型表示日期(年、月、日)。main中輸入一個日期,計算該日期是當年的第幾天。
</pre><p></p><p><pre name="code" class="plain">#include<stdio.h>

int runnian( int x);      // 判斷閏年
int day(struct Date *p);  <span style="white-space:pre">	</span>// 計算天數, 傳遞結構體, 注意參數的類型

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


int main()
{
	struct Date time;
	int days;
	days = 0;

	printf("Input a date: ");
	scanf("%d-%d-%d", &time.year, &time.month, &time.day);
	
	days = day(&time);

	printf("days of the year = %d\n", days);
	
	return 0;
}
int day(struct Date *p)
{
	int num = 0;
	int i;
	for(i = 0; i < p->month; i++)
	{
		if(i == 1 || i == 3 || i == 5 || i == 7 || i == 8 || i == 10 || i == 12)
		{
			num += 31;
		}
		else if( i == 4 || i == 6 || i == 9 || i == 11)
		{
			num += 30;
		}
	}
	num += p->day;
	if(p->month > 2)
	{
		num += runian(p->year);
	}
	return num;
}
int runian( int x)
{
	if(x % 400 == 0)
	{
		return 29;
	}
	else
	{
		if(x % 100 != 0 && x % 4 == 0)
		{
			return 29;
		}
	}

	return 28;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章