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

2024-04-28 22:32:58 发布

您现在位置:Python中文网/ 问答频道 /正文

希望你们今天过得愉快。我在学习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."   

我也会很感激任何关于使这段代码更干净的提示。i、 可读性更强或者工作效率更高。谢谢。在


Tags: andthetoinputrawreturndef整数