计算机导论课第二次作业 (Past)

10205102406 edited 4 年,1 月前

This is a past version of blog 计算机导论课第二次作业

1、略

2、
‘’‘
def sqr(x):
x = abs(x)
res = 0
for i in range(x):
res += x
return res

def cube(x):
t = sqr(x)
res = 0
for i in range(abs(x)):
res += t
if x > 0:
return res
else:
return -res

def quad(x):
if x == 0:
return 0
else:
return int(sqr(x)/(1/sqr(x)))

print(sqr(5), sqr(-5))
print(cube(5), cube(-5))
print(quad(5), quad(-5))

’‘’
avatar

3、
‘’‘
def factor(n):
res = n
for i in range(2,n):
res *= i
return res

def combination(n, k):
return int(factor(n)/(factor(n-k)*factor(k)))

print(factor(4))
print(combination(4, 2))
‘’‘
avatar

4、因为3/x不是整除,会有小数点,x太大的时候因为浮点数精度不足就把3/x当成0了,所以3/x+1就是1啦,但是x不够大的时候3/x就没有被当做0,还有一点点,所以3/x+1就大于1,而不是等于1啦。

5、
‘’‘
print(2**10)
print(2**20)
print(2**30)
print(2**40)
print(2**50)
‘’‘
avatar

6、
‘’‘
def square_root_1():
c = 10
i = 0
g = 0

while (g+1)**2 < c:
    g+=1

while (abs(g*g-c) > 0.0001):
    g += 0.00001
    i = i+1
    print("% d:g = %.5f" % (i,g))

square_root_1()
‘’‘
avatar

7、
‘’‘
def square_root_2():
i = 0
c = 0.9
m_max = c if c>1 else 1
m_min = 0
g = (m_min + m_max)/2
while(abs(gg-c) > 0.00000000001):
if(g
g<c):
m_min = g
else:
m_max = g
g = (m_min + m_max)/2
i = i+1
print(“%d:%.13f” % (i,g))

square_root_2()
‘’‘
avatar

8、
‘’‘
x = 1
c = 0
i = 1.5
while abs(x-i) > 0.112:
x = i
if x
3+x2-10 > 0:
i = x - 0.5
(c+2)
else:
i = x + 0.5 ** (c+2)
c+=1
print(“二分法结果为%.12f,共迭代%d次”%(i,c))

x = 1
c = 0
i = 1.5
while abs(x-i) > 0.112:
x = i
i = x-(x
3+x2-10)/(3*x2+2*x)
c+=1
print(“牛顿法结果为%.12f,共迭代%d次”%(i,c))
‘’‘
avatar

9、
‘’‘
A = [[1,2,6],
[2,4,12]]

D = A[0][0]A[1][1] - A[0][1]A[1][0]
Dx = A[0][2]A[1][1] - A[0][1]A[1][2]
Dy = A[0][0]A[1][2] - A[0][2]A[1][0]

if D == 0:
if Dx == 0 and Dy == 0:
print(“方程有无穷解”)
else:
print(“方程无解”)
else:
print(“方程有解:x = %f, y = %f” %(Dx/D, Dy/D))
‘’‘
avatar

10、
‘’‘
s = “I am a Chinese “
res = []

word = “”
for i in s:
if i == ‘ ‘:
if word:
res.insert(0, word)
word = “”
else:
word += i
if word:
res.insert(0, word)

print(res)
‘’‘
avatar

11、
‘’‘
s = “ABABA”
if s == s[::-1]:
print(True)
else:
print(False)
‘’‘
avatar

12、略

编辑者:姜博远