问题求解——自定义函数

第1关 定义自己的print函数

########## Begin ##########

def myprint(x):
    if type(x)==float:
        print('%.3f' % x)
    else:
        print(x)

########## End ##########
r, pi=3, 3.141592653589793
myprint('半径r:')
myprint(r)
myprint('\n圆的面积S:')
myprint(pi*r**2)

第2关 温度对照表

########## Begin ##########
def printOneRow(x):
    print('%3d     %3d' % (x,int(1.8*x+32)))

########## End ##########
print('%3s     %3s' % ('C', 'F')) #打印第1行的表头
print('------------')             #打印第2行的分隔线
for C in range(0, 101, 10):       #依次打印数据行
    printOneRow(C)

第3关 计算向量模

########## Begin ##########


def norm(x):
    ans=0
    for i in x:
        ans=ans+i*i
    ans=ans**(0.5)
    x=round(ans,2)
    return x
########## End ##########
x1 = [3, 4]
x2 = [1, 2, 3]
x3 = [1, 2, 3, 5, 6, 7, 8]
print('||x1|| = %.2f' % norm(x1))
print('||x2|| = %.2f' % norm(x2))
print('||x3|| = %.2f' % norm(x3))

第4关 求阶乘之和

########## Begin ##########

def fac(x):
    ans=1
#   自己编写
    return ans
########## End ##########
n = int(input())
s = 0
for x in range(1, n+1):
    s = s+fac(x)
print('1到%d的阶乘之和为:%d' % (n, s))

第5关 用泰勒级数求余弦值

########## Begin ##########
def fac(x):
    #自己编写
    return ans

def mycos(x,n=10):
    ans=0
    for i in range(0,n+1):
        ans=ans+((-1)**i)*x**(2*i)/fac(2*i)
    return ans

########## End ##########
pi = 3.14159
x  = pi/3
for n in range(5):
    print('n=%d时,cos(60°)=%.5f' % (n, mycos(x, n)))

print('-'*30)
L = [0, 30, 45, 60, 90]
for x in L:
    print('cos(%d°)=%.5f' % (x, mycos(x*pi/180)))

第6关 绘制迫击炮弹运行轨迹

########## Begin ##########
########## Begin ##########
import numpy as np
import matplotlib.pyplot as plt

v0=50
g=9.8

def fuc(si,t):
    #自己编写
    return xt,yt

L=[30,45,60,75]
for i in L:
    si=np.radians(i)
    sin=np.sin(si)
    cos=np.cos(si)
    t=v0*2*sin/g
    T=np.linspace(0,t,30)
    xt,yt=fuc(i,T)
    plt.plot(xt,yt,'r-')

plt.grid(True)
plt.axis([0, 260, 0, 120])
plt.show()
########## End ##########
########## End ##########
plt.savefig( 'src/step6/student/pic.png' )
plt.close()
posted @ 2026-11-04 18:30  qtanglani  阅读(10)  评论(0)    收藏  举报