24、计算表示一定数量美分所需的最少硬币组合。这里涉及的硬币有两加元硬币(toonies,每个价值200美分)、一加元硬币(loonies,每个价值100美分)、两角五分硬币(quarters,每个价值25美分)、一角硬币(dimes,每个价值10美分)、五分硬币(nickels,每个价值5美分)和一分硬币(pennies,每个价值1美分)。
以下是对应的Python代码实现:
CENTS_PER_TOONIE = 200
CENTS_PER_LOONIE = 100
CENTS_PER_QUARTER = 25
CENTS_PER_DIME = 10
CENTS_PER_NICKEL = 5
# 从用户处读取美分数量
cents = int(input("Enter the number of cents: "))
# 确定两加元硬币的数量并计算剩余美分
print(" ", cents // CENTS_PER_TOONIE, "toonies")
cents = cents % CENTS_PER_TOONIE
# 对一加元硬币、两角五分硬币、一角硬币和五分硬币重复此过程
print(" ", cents // CENTS_PER_LOONIE, "loonies")
cents = cents % CENTS_PER_LOONIE
print(" ", cents // CENTS_PER_QUARTER, "quarters")
cents = cents % CENTS_PER_QUARTER
print(" ", cents // CENTS_PER_DIME, "dimes")
cents = cents % CENTS_PER_DIME
print(" ", cents // CENTS_PER_NICKEL, "nickels")
cents = cents % CENTS_PER_NICKEL
# 显示一分硬币的数量
print(" ", cents, "pennies")
这段代码通过不断地进行整除和取余运算,逐步计算出表示给定美分数量所需的最少硬币组合。
25、将以英尺和英寸为单位的身高转换为厘米
# Read the height from the user
print("Enter your height:")
feet = int(input("Number of feet: "))
inches = int(input("Number of inches: "))
# Compute the equivalent number of centimeters
IN_PER_FT = 12
CM_PER_IN = 2.54
cm = (feet * IN_PER_FT + inches) * CM_PER_IN
# Display the result
print("Your height in centimeters is:", cm)
26、计算加热一定体积的水所需的能量以及这样做的成本。已知水的比热容为 4.186 J/(g·℃),1 毫升水的质量为 1 克,电价为每千瓦时 8.9 美分,1 焦耳等于 2.777×10⁻⁷ 千瓦时。
# Define constants for the specific heat capacity of water and the price of electricity
WATER_HEAT_CAPACITY = 4.186
ELECTRICITY_PRICE = 8.9
J_TO_KWH = 2.777e-7
# Read the volume and temperature increase from the user
volume = float(input("Amount of water in milliliters: "))
d_temp = float(input("Temperature increase (degrees Celsius): "))
# Compute the energy in Joules
q = volume * d_temp * WATER_HEAT_CAPACITY
# Display the result in Joules
print("That will require %d Joules of energy." % q)
# Compute the cost
kwh = q * J_TO_KWH
cost = kwh * ELECTRICITY_PRICE
# Display the cost
print("That much energy will cost %.2f cents." % cost)
27、计算一个物体被扔下后撞击地面时的速度。已知物体从静止开始下落,不考虑空气阻力,重力加速度取 9.8 m/s²。
以下是解决该问题的 Python 代码:
from math import sqrt
# Define a constant for the acceleration due to gravity in m/s**2
GRAVITY = 9.8
# Read the height from which the object is dropped
d =

最低0.47元/天 解锁文章

被折叠的 条评论
为什么被折叠?



