gpt4 book ai didi

Python:浮点输入作为整数输出返回?

转载 作者:太空宇宙 更新时间:2023-11-04 10:31:56 25 4
gpt4 key购买 nike

我希望你们都度过了充实的一天。我正在学习 python,我写了这个小欧姆定律计算器作为学习练习。该程序运行良好,但即使我将用户输入转换为“ float ”,函数也只返回整数答案。 (例如,如果我选择电压并输入 0.7 安培,它会返回一个不正确的整数)这是我的代码:

# ohm's law calculator

# These functions perform the calculations, but the result currently only prints as an integer.
def voltage(i, r):
return i * r



def current(r, v):
return r / v


def resistance(i, v):
return i / v




# First user interface menu

print "What value would you like to solve for?"

print "1. Voltage"
print "2. Current"
print "3. Resistance"

choice = raw_input(">>> ")



#These are calling the functions.

#This gives values to "i" and "r" from user input as floating point numbers the print line calls the "voltage" function and prints out the results of its calculation using "%d"
if choice == "1":
i=float(raw_input("Enter current:"))
r=float(raw_input("Enter resistance:"))
print "%d volts" % voltage(i, r)


elif choice == "2":
r=float(raw_input("Enter resistance:"))
v=float(raw_input("Enter voltage:"))
print "%d amps" % current(r, v)



elif choice == "3":
i=float(raw_input("Enter current:"))
v=float(raw_input("Enter voltage:"))
print "%d ohms" % resistance(i, v)

#This line is here partly because its funny, and partly because I thought it would be cool to create my own error message
else:
print "Invalid number. Your system will crash momentarily."

如果有任何使此代码更简洁的提示,我也将不胜感激。我。 e.更具可读性或工作效率更高。谢谢。

最佳答案

不要使用 %d 输出 float ,使用 %f

最好还是使用新的 format 函数,让 Python 选择最佳表示:

print "{0} volts".format(voltage(i, r))

关于Python:浮点输入作为整数输出返回?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25878870/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com