1. 程式人生 > 其它 >[PTA]練習7-9 計算天數

[PTA]練習7-9 計算天數

[PTA]練習7-9 計算天數

本題要求編寫程式計算某年某月某日是該年中的第幾天。

輸入格式:
輸入在一行中按照格式“yyyy/mm/dd”(即“年/月/日”)給出日期。注意:閏年的判別條件是該年年份能被4整除但不能被100整除、或者能被400整除。閏年的2月有29天。

輸出格式:
在一行輸出日期是該年中的第幾天。

輸入樣例1:
2009/03/02
輸出樣例1:
61
輸入樣例2:
2000/03/02
輸出樣例2:
62

  • 執行示例1:

在這裡插入圖片描述

  • 執行示例2:

在這裡插入圖片描述

  • 原始碼:
#include<stdio.h>
int isLeapYear(int year);   // 函式定義
int main(void)
{
	char date[
10]; int year, month, day, countDay; int dayInMonth[13] = { 0,31,0,31,30,31,30,31,31,30,31,30,31 }; // 月份對應天數,2月天數暫為0,後續判斷後賦值 for (int i = 0; i < 10; i++) // 獲取輸入的字串 { date[i] = getchar(); } year = (date[0] - '0') * 1000 + (date[1] - '0') * 100 + (date[2] - '0') * 10 + (date[3] - '0'); // 通過ASCII碼轉換,計算年份 month =
(date[5] - '0') * 10 + (date[6] - '0'); // 計算月份 day = (date[8] - '0') * 10 + (date[9] - '0'); //計算天數 countDay = 0; if (isLeapYear(year) == 1) // 該年是閏年,2月有29天 { dayInMonth[2] = 29; } else // 非閏年,2月有28天 { dayInMonth[2] = 28; } for (int i = 1; i < month; i++) // 計算month前幾個月的天數和 { countDay +
= dayInMonth[i]; } // 加上month該月的天數 countDay += day; printf("%d", countDay); return 0; } // 函式名:isLeapYear // 功能:根據傳入的年份值,判斷該年是否是閏年,是則返回1,否則返回0; // 引數:year年份值 // 返回值:1:是閏年; 0:不是閏年 int isLeapYear(int year) { if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) { return 1; } return 0; }