Python数学除法运算返回0

时间:2016-01-06 00:03:03

标签: python division

print "------------ EPIDEMIOLOGY --------------\n"

def divide(A,B):
    return A/B

print " [Population] point Prevalence rate: "
A = input("Enter value for people with disease: " )
B = input("Enter value for total population: " )    
prevalence = divide(A,B)
print " Population Prevalence rate is: ",prevalence

A和B是用户输入,不知道它们是整数还是浮点数。当我运行这个程序时,我的答案总是0。 (我是Python新手)。我如何修复此问题或更改我的功能以避免此问题?

代码的输入部分有效,数学没有。

2 个答案:

答案 0 :(得分:5)

您得到答案0,因为您正在使用Python2并执行整数除法。疾病人群不能高于总人口的事实是每次合理输入都得零的原因(除非两个值相同)。

两个修正:

def divide(a,b):
    if b == 0:
        # decide for yourself what should happen here
    else:
        return float(a)/b

这将确保您的函数执行浮点除法,而不管您传递给它的数字。第二个修复是你应该在Python2中使用raw_input并将输入转换为数字(float在这里没问题。)

a = float(raw_input("Enter value for people with disease: ")) # add error checking as needed
b = float(raw_input("Enter value for total population: " )) # add error checking as needed

input()的问题在于它等同于eval(raw_input())

答案 1 :(得分:3)

在python 2.x中执行整数除法。如果股息小于除数,则操作返回零 所以你有两个选择:

将其中一个操作数设为float:

def divide(A,B):
    return float(A)/B
Python 3的

导入功能

from __future__ import division

print "------------ EPIDEMIOLOGY --------------\n"

def divide(A,B):
    return A/B
相关问题