2018-05-24
2018-05-24 本文已影响0人
BD_1
一、万年历
它的功能是:用户输入某年、某月、某日,程序输出这一天是星期几;用户输入某年、某月,程序输出该年该月的每一天是星期几;用户输入某年,程序输出该年每一月的每一天是星期几。
该程序的求解方案是,为给定的年、月、日计算它距离1900年1月1日(它是星期一)的天数,从而得出是星期几;注意要考虑闰年的情况。
def leap_year(year):
if year%4 == 0 and year%100 != 0 or year%400 == 0:
return True
else:
return False
def days_of_month(year,month):
days = 31
if month == 2:
if leap_year(year):
days = 29
else:
days = 28
elif month == 4 or month == 6 or month == 9 or month == 11:
days = 30
return days
def totaldays(year,month,day):
totaldays = 0
for i in range(1900,year):
if leap_year(i):
totaldays += 366
else:
totaldays += 365
for j in range(1,month):
totaldays += days_of_month(year,j)
totaldays = totaldays+day-1
return totaldays
def print_month(year,month):
print ("一 二 三 四 五 六 日")
print (totaldays(year,month,1)%7*' ',end="")
for i in range(1,days_of_month(year,month)+1):
if i < 10:
print(i,3*" ",end="")
else:
print(i,2*" ",end="")
if (totaldays(year,month,i)+1)%7 == 0:
print(" ")
choice = int(input("年份日历请选1,月份日历请选2,某天周几请选3:"))
if choice == 1:
year = int(input("请输入年份:"))
for month in range(1,13):
print("2018年"+str(month)+"月")
print(print_month(year,month))
if choice == 2:
year = int(input("清输入年份:"))
month = int(input("请输入月份:"))
print(print_month(year,month))
elif choice == 3:
year = int(input("清输入年份:"))
month = int(input("请输入月份:"))
day = int(input("请输入一月中的第几天:"))
weekday = totaldays(year,month,day)%7+1
print("这一天是星期"+str(weekday))
else:
print("请输入1到3的数字!")
二、泰勒法求e值
问题: e = 1 + 1/1! + 1/2! + 1/3! + ... (≈𝟐.𝟕𝟏𝟖𝟐𝟖…) 基于上式求e(自然常数)的近似值,要求最后一项都大于等于10-4
def abc(n):
if n == 1:
return 1
return n*abc(n-1)
for n in range(1,10000):
if 1/abc(n) < 0.1**4:
x = n
break
e = 1
for n in range(1,x+1):
e += 1/abc(n)
print(e)