我希望你们都度过了充实的一天。我正在学习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."
我也很感激有关使这段代码更清洁的任何提示。一世。即更具可读性或工作效率更高。感谢。
答案 0 :(得分:4)
请勿使用%d
输出浮点数,请使用%f
。
更好的是使用新的format
函数,让Python选择最佳表示:
print "{0} volts".format(voltage(i, r))