可分性检查器十进制和负数

时间:2014-06-03 22:14:15

标签: python

我正在努力让我的divisibility checker代码正常工作。它目前只适用于整数正数。如果数字是小数或负数,则代码将不起作用。我知道我需要添加一些花车,但我不知道在哪里添加它们。

def divisibility():
        print "+------------------------------------+"
        print "|Welcome to the Divisibility Checker!|"
        print "+------------------------------------+"

        x = raw_input("Please input a number: ")
        num1 = raw_input("Number to start checking at: ")
        num2 = raw_input("Number to end checking at: ")

        print "Divisibility:"
        for i in range(int(num1), int(num2)):
                if (int(i)) % (int(x)) == 0:
                        print str(i) + ": Yes"
                else:
                        pass
divisibility()

我想要它做什么基本上打印哪些数字可被这个数字整除。因此,如果您输入2.5,然后您希望它从1-10检查它应该返回2.5,5,7.5和10.就像您输入-2,它从0 - ( - 10)检查它应该返回-2,-4,-6,-8和-10。

2 个答案:

答案 0 :(得分:0)

根据OP的例子,他似乎希望获得两个范围之间的数字的所有整数倍。鉴于这一目标,我已重命名函数getMultiples

from math import ceil
from math import floor


def getMultiples(x, num1, num2):
    num1, num2 = min(num1, num2), max(num1, num2)

    lower = ceil(float(num1) / x)
    upper = floor(float(num2) / x)
    lower, upper = min(lower, upper), max(lower, upper)

    for i in range(int(lower), int(upper) + 1):
       print i * x

getMultiples(2.5, 1, 10)
getMultiples(-2, 0, -10)

输出:

2.5
5.0
7.5
10.0
0
-2
-4
-6
-8
-10

答案 1 :(得分:0)

有更好的方法来实现你想要做的事情,正如Merlins的答案所示,但我认为作为初学者,你对学习更感兴趣而不是熟练。

此代码不完整,但应该足以让您开始接近您想要的内容。

def float_range(start, stop, step): # will step in  any range of step passed 1, .5, .1 etc...
    while start < stop:
        yield start
        start += step


def divisibility():
    print "+------------------------------------+"
    print "|Welcome to the Divisibility Checker!|"
    print "+------------------------------------+"

    x = raw_input("Please input a number: ")
    num1 = (raw_input("Number to start checking at: "))
    num2 = (raw_input("Number to end checking at: "))
    if "." in num1:    # if "." is in the num it is a float
        num1 = float(num1)
    else:               # else an int
        num1 = int(num1)
    if "." in num2:
        num2 = float(num2)
    else:
        num2 = int(num2)
    if "." in x:
        x = float(x)
        step=.5     # you will need more conditions to check and set the appropriate step.
    else:
        x = int(x)
        step=1
    print "Divisibility:"

    for i in float_range(num1, num2 + 1,step=step): # add 1 to range to include top end of range
        if i % x == 0:
            print str(i) + ": Yes"

divisibility()