Python第二章課本習題參考
第一題
一元二次方程式的公式解 (a !=0):
import math a, b, c = eval(input('Input a, b, and c:')) deter = b*b - 4*a*c if deter > 0: answer1 = (-b + math.sqrt(deter)) / (2*a) answer2 = (-b - math.sqrt(deter)) / (2*a) print('The solution are %f and %f' %(answer1, answer2)) elif deter == 0: answer = -b /(2*a) print('The solution is %f' %(answer)) else: print('No solution!')2nd 寫一程式,輸入一個點的座標(x, y),輸出這個點是否在圓心(0,0),半徑8的圓的內部或外部。
import math x, y = eval(input('Input x and y :')) d = math.sqrt(x**2 + y**2) if d < 8: print('The point (%d, %d) is inside of the circle' %(x,y)) else: print('The point (%d, %d) is not inside of the circle' %(x,y))
import random r = random.randint(1, 100) r3 = r % 3 r5 = r % 5 if r3 == 0 and r5 == 0 : print('%d 是 3 而且 也是 5 的倍數' %(r)) elif r3 != 0 and r5 != 0 : print('%d 不是 3 而且 也不是 5 的倍數' %(r)) elif r3 == 0: print('%d 是 3 的倍數' %(r)) elif r5 == 0: print('%d 是 5 的倍數' %(r))
# 將使用者輸入的十六進位的字元轉換為其十進位所對應的數值 c = input('請輸入一個字元:') if c >= '0' and c <= '9': print('對應的十進位值是 %d' %(ord(c) - ord('0'))) elif c >= 'A' and c <= 'F': print('對應的十進位值是 %d' %(ord(c) - ord('A') + 10)) elif c >= 'a' and c <= 'f': print('對應的十進位值是 %d' %(ord(c) - ord('a') + 10))