python
def mix_volumes(c1, v1, c2, v2):
total_alc = c1 v1 + c2 v2
total_vol = v1 + v2
return total_alc / total_vol if total_vol != 0 else 0
def calculate_required_volume(c1, v1, c2, c_target):
if (c_target < min(c1, c2)) or (c_target > max(c1, c2)):
return None
denominator = c_target
if denominator == 0:
return None
v2 = (c1
return v2 if v2 >= 0 else None
def calculate_ratio(c1, c2, c_target):
if (c_target < min(c1, c2)) or (c_target > max(c1, c2)):
return None
numerator = c_target
denominator = c1
if denominator == 0:
return None
ratio = numerator / denominator
return ratio if ratio >= 0 else None
def get_float_input(prompt):
while True:
try:
value = float(input(prompt))
return value if value >= 0 else (print("输入不能为负数。") or get_float_input(prompt))
except ValueError:
print("输入无效,请输入数字。")
def main:
print("白酒勾兑计算器")
while True:
print("
请选择功能:
2. 计算需要添加的酒量
3. 计算混合比例
4. 退出")
choice = input("请输入选项(1/2/3/4): ").strip
if choice == '4':
print("退出程序。")
break
elif choice == '1':
print("
功能1:计算混合后的酒精度")
c1 = get_float_input("酒A的度数(%): ")
v1 = get_float_input("酒A的体积(ml): ")
c2 = get_float_input("酒B的度数(%): ")
v2 = get_float_input("酒B的体积(ml): ")
final = mix_volumes(c1, v1, c2, v2)
print(f"混合后酒精度: {final:.1f}%")
elif choice == '2':
print("
功能2:计算需要添加的酒量")
c_known = get_float_input("已知酒的度数(%): ")
v_known = get_float_input("已知酒的体积(ml): ")
c_other = get_float_input("另一酒的度数(%): ")
c_target = get_float_input("目标酒精度(%): ")
v_other = calculate_required_volume(c_known, v_known, c_other, c_target)
print(f"需要添加的{c_other}%酒: {v_other:.1f}ml" if v_other is not None else "无法达到目标酒精度")
elif choice == '3':
print("
功能3:计算混合比例")
c1 = get_float_input("酒A的度数(%): ")
c2 = get_float_input("酒B的度数(%): ")
c_target = get_float_input("目标酒精度(%): ")
ratio = calculate_ratio(c1, c2, c_target)
if ratio is not None:
print(f"混合比例:酒A:酒B = {ratio:.1f}:1" + (f" 或 1:{1/ratio:.1f}" if ratio != 0 else ""))
else:
print("无法达到目标酒精度")
else:
print("无效选项")
if input("
继续计算?(y/n): ").lower != 'y':
print("退出程序。")
break
if __name__ == "__main__":
main
功能说明:
1. 混合酒精度计算:输入两种酒的度数和体积,计算混合后的酒精度。
2. 所需酒量计算:输入已知酒的参数和目标酒精度,计算需要添加的另一酒的体积。
3. 混合比例计算:输入两种酒的度数,计算达到目标酒精度所需的混合比例。
使用示例:
1. 计算混合酒精度:
2. 计算所需酒量:
3. 计算混合比例:
该脚本可处理常见的勾兑计算需求,并包含输入验证和错误提示。