您好,登錄后才能下訂單哦!
本篇內(nèi)容介紹了“怎么用Python計(jì)算某日是該年的第幾天”的有關(guān)知識(shí),在實(shí)際案例的操作過(guò)程中,不少人都會(huì)遇到這樣的困境,接下來(lái)就讓小編帶領(lǐng)大家學(xué)習(xí)一下如何處理這些情況吧!希望大家仔細(xì)閱讀,能夠?qū)W有所成!
編寫一個(gè)計(jì)算天數(shù)的程序,用戶從鍵盤中輸入年、月、日,在屏幕中輸出此日期是該年的第幾天。
C代碼:
/*第三天、計(jì)算某日是該年的第幾天*/#include <stdio.h>#include <stdlib.h>int main(void) {/*參數(shù)依次為年、月、日、計(jì)算天數(shù)、for循環(huán)初始值*//*注意:days賦初始值0,不賦值,變量的值不確定,會(huì)導(dǎo)致運(yùn)行崩潰*/int year,month,day,days = 0,i = 0;int average_year[12] = { 31,28,31,30,31,30,31,31,30,31,30,31}; //平年int leap_year[12] = { 31,29,31,30,31,30,31,31,30,31,30,31}; //閏年printf("請(qǐng)輸入要查詢的日期,例如:1993年1月30日\(chéng)n");scanf("%d年%d月%d日",&year,&month,&day);/*能被400整除,或者不能被100整除但能被4整出的年份為閏年*/if(year % 400 == 0 || year % 4 == 0 && year % 100 != 0) {/*數(shù)組的第一個(gè)元素的索引值為0,將month月的前幾個(gè)月相加*/for(i;i <= month - 2;i++) days += leap_year[i];/*將month月的day天加上,為最終的天數(shù)*/days += day; }else /*不滿足,則為平年*/{/*同上*/for(i;i <= month - 2;i++) days += average_year[i]; days += day; }printf("%d年%d月%d日是%d年的第%d天\n",year,month,day,year,days); system("pause"); }
結(jié)果顯示:
python代碼,C代碼的升級(jí)版,可以進(jìn)行輸入判斷:
def leap(a):if (a % 4 == 0) & (a % 100 != 0) | (a % 400 == 0):return 1else:return 0def number(y,m,d):result = 0average_year = (31,28,31,30,31,30,31,31,30,31,30,31) #平年的元組leap_year = (31,29,31,30,31,30,31,31,30,31,30,31) #閏年的元組if (1 <= y <= 5000) & (1 <= m <= 12) & (1 <= d <=31) & leap(y) & (d <= leap_year[m-1]):for i in range(0,m-1): result += leap_year[i]elif (1 <= y <= 5000) & (1 <= m <= 12) & (1 <= d <=31) & (leap(y) == 0) & (d <= average_year[m-1]):for i in range(0,m-1): result += average_year[i]else: result = 0d = 0result += dreturn resultdef tranform(contents):if ('年' in contents) & ('月'in contents) & ('日' in contents) & (' ' not in contents): str_len = len(contents)for i in range(1,str_len):if contents[i] == '年': year = int(contents[0:i]) #input()接收的是字符串year_num = i + 1if contents[i] == '月': month = int(contents[year_num:i]) #用int()強(qiáng)制轉(zhuǎn)換成整型month_num = i + 1if contents[i] == '日': day = int(contents[month_num:i])return (year,month,day)else:return 0choose = 1 while choose: contents = input('請(qǐng)輸入要查詢的日期,查詢范圍公元1年-公元5000年,例如:1993年1月30日\(chéng)n') t = tranform(contents)if t != 0: result = number(t[0],t[1],t[2])if result != 0: print('第%d天' %(result))while True: choose = input('輸入‘是’繼續(xù)查詢,輸入‘否’放棄查詢\n')if ('是' in choose) | ('否' in choose) & (len(choose) == 1):if '是' in choose: choose = 1breakelse: choose = 0breakelse: print('輸入選擇錯(cuò)誤,請(qǐng)重新輸入\n')else: print('輸入日期錯(cuò)誤,請(qǐng)重新輸入\n')else: print('輸入格式錯(cuò)誤,請(qǐng)重新輸入\n')
結(jié)果顯示:
“怎么用Python計(jì)算某日是該年的第幾天”的內(nèi)容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業(yè)相關(guān)的知識(shí)可以關(guān)注億速云網(wǎng)站,小編將為大家輸出更多高質(zhì)量的實(shí)用文章!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。