python:如何只输出整数和浮点数列表中的整数

时间:2017-03-30 01:59:27

标签: python python-3.x

我有问题。我想知道是否有一种方法只能在整数和浮点数列表中输出整数。

这是我到目前为止所写的内容:(关于它是如何格式化的) -

# Greet the user
print("Welcome to the Common Divisors Machine!")

# Initialize variable
confirm = 'yes'

# Start nested checking against variable to start or not
while confirm != ('n' or 'N' or 'no' or 'No'):
    x = int(input("Please enter the first number: "))

    # Validating the variable "x"
    while x <= 0:
        x = int(input("Error, please enter a positive, non-zero number: "))
    # Initializing for the first part of the FOR loop
    i = 1
    y = int(input("Please enter the second number: "))

    # Validating the variable "y"
    while y <= 0:
        y = int(input("Error, please enter a positive, non-zero number: "))
    # Initializing variable for the second part of the FOR loop
    h = 1
    print("The common divisors, excluding 1 and 2, are: ")
    # Starting the FOR loop
    # Setting the variable initialized earlier to be used against "x"
    for i in range (1, x - 1):
        # Nested the second part to run within the first part
        for h in range (1, y - 1):
            # Dividing the user input
            a = x / i
            b = y / h

            # Nesting a WHILE loop to run within both of the FOR loops
            # to print the output of both
            # Also checking whether the answers are the same
            while a == b and a != 1 and a != 2:
                # Printing the output
                print(b)
                # Re initializing "a" so that it will loop back to the top
                a = 0

    # Checking whether or not the user would like to check for more divisors
    confirm = input("Would you like to continue(y/n)? ")
 # Exiting comment
print("Thank you for using the Common Divisors Machine!")

这甚至可能吗?

这是一个示例输出,用于询问:

Welcome to the Common Diviors Machine!
Please enter the first number: 150
Please enter the second number: 300
The common divisors, excluding 1 and 2, are: 
150.0
75.0
50.0
37.5
30.0
25.0
21.428571428571427
18.75
16.666666666666668
15.0
13.636363636363637
12.5
11.538461538461538
10.714285714285714
10.0
9.375
8.823529411764707
8.333333333333334
7.894736842105263
7.5
7.142857142857143
6.818181818181818
6.521739130434782
6.25
6.0
5.769230769230769
5.555555555555555
5.357142857142857
5.172413793103448
5.0
4.838709677419355
4.6875
4.545454545454546
4.411764705882353
4.285714285714286
4.166666666666667
4.054054054054054
3.9473684210526314
3.8461538461538463
3.75
3.658536585365854
3.5714285714285716
3.488372093023256
3.409090909090909
3.3333333333333335
3.260869565217391
3.1914893617021276
3.125
3.061224489795918
3.0
Would you like to continue(y/n)? 

我不希望它显示长小数,只显示整数

1 个答案:

答案 0 :(得分:0)

我认为你要问的是,“我如何确定一个数字是否可以被另一个数字整除?”

该问题的答案是modulo operator: %

模运算基本上在两个数的除法后返回整数余数。因此6 % 5的结果为1,7 % 5为2,等等。

您可以检查是否a % b == 0以确定是,a可被b整除。