本篇内容介绍了“怎么用Python计算某日是该年的第几天”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!
编写一个计算天数的程序,用户从键盘中输入年、月、日,在屏幕中输出此日期是该年的第几天。
C代码:
/*第三天、计算某日是该年的第几天*/#include <stdio.h>#include <stdlib.h>int main(void) {/*参数依次为年、月、日、计算天数、for循环初始值*//*注意:days赋初始值0,不赋值,变量的值不确定,会导致运行崩溃*/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("请输入要查询的日期,例如:1993年1月30日\n");scanf("%d年%d月%d日",&year,&month,&day);/*能被400整除,或者不能被100整除但能被4整出的年份为闰年*/if(year % 400 == 0 || year % 4 == 0 && year % 100 != 0) {/*数组的第一个元素的索引值为0,将month月的前几个月相加*/for(i;i <= month - 2;i++) days += leap_year[i];/*将month月的day天加上,为最终的天数*/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"); }
结果显示:
python代码,C代码的升级版,可以进行输入判断:
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()强制转换成整型month_num = i + 1if contents[i] == '日': day = int(contents[month_num:i])return (year,month,day)else:return 0choose = 1 while choose: contents = input('请输入要查询的日期,查询范围公元1年-公元5000年,例如:1993年1月30日\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('输入‘是’继续查询,输入‘否’放弃查询\n')if ('是' in choose) | ('否' in choose) & (len(choose) == 1):if '是' in choose: choose = 1breakelse: choose = 0breakelse: print('输入选择错误,请重新输入\n')else: print('输入日期错误,请重新输入\n')else: print('输入格式错误,请重新输入\n')
结果显示:
“怎么用Python计算某日是该年的第几天”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识可以关注亿速云网站,小编将为大家输出更多高质量的实用文章!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。