如何解决这种情况,而while循环不会取0或值不小于0?

时间:2019-03-27 01:46:10

标签: python python-3.x

我无法计算,而while循环中的哨兵值等于或小于0 所需纵向总长度= 6 m 所需的横向总长度= 5 m

Problem Statment

程序能够满足长度条件,并且在循环中面包等于0,但不小于0的负数

我无法计算总长度并将其设为整数。

length = float    
width = float    
sentinal = 0    
d1 = 1

d2 = 1
for i in range(20):

    while d1 != sentinal and d2 != sentinal:

        d1 = float(input("enter room dimension1 (m):"))

        d2 = float(input("enter room dimension2 (m):"))

        if d1 > d2:

                length = d1

                width = d2

                print("length = %.3f m" %(length))

                print("width = %.3f m" %(width))

        elif d2 > d1:

                length = d2

                width = d1

                print("length = %.3f m" %(length))

                print("width = %.3f m"%(width))

3 个答案:

答案 0 :(得分:1)

请注意:如果这是一项家庭作业,请不要在不了解所有内容的情况下盲目复制代码,我会尽力通过#注释来解释代码

import math  # required to use ceil() function , ex: ceil(3.2) = 4

def required_length(a, b):  # functions make your code organized
    length = max(a,b)
    width = min(a,b)
    print('length = ', length)
    print('width = ', width)
    print('Total length required lengthways = ', math.ceil(length))
    print('Total length required widthways = ', math.ceil(width))
    print()  # to look nice  print empty line for getting new input


while True:  # loop forever
    a = float(input('enter room dimension 1 (m): '))
    b = float(input('enter room dimension 2 (m): '))

    if a <= 0 or b <= 0:  # exit loop if user entered zero or minus
        print('invalid dimensions')
        break

    required_length(a, b)  # call our function

答案 1 :(得分:0)

    sentinal = 0
    d1 = 1.0
    d2 = 1.0
    while d1 > sentinal and d2 > sentinal:

        d1 = float(input("enter room dimension1 (m):"))

        d2 = float(input("enter room dimension2 (m):"))

        if d1 > d2:

                length = d1

                width = d2

                print("length = %.3f m" %(length))

                print("width = %.3f m" %(width))
                print("Total length required lengthways: ", int(length)+1))
                print("Total length required widthways: ", int(width)+1))


        else:

                length = d2

                width = d1

                print("length = %.3f m" %(length))

                print("width = %.3f m"%(width))
                print("Total length required lengthways: ", int(length)+1))
                print("Total length required widthways: ", int(width)+1))

答案 2 :(得分:0)

只写了一个优化代码

sentinal = True    
while sentinal:
        d1 = float(input("enter room dimension1 (m): "))
        d2 = float(input("enter room dimension2 (m): "))
        if 0 in (d1,d2) or 0.0 in (d1,d2):
            sentinal=False
        else:
            length, width = (d1,d2) if d1>d2 else  (d2,d1)
            print("leangth = %.3f m" %(length))
            print("width = %.3f m" %(width))