我已经写了这个程序,它询问用户他们想要打印出多少个矩形。它还会询问每个三角形的宽度和高度,并打印三角形。在询问每个矩形的高度和宽度后,它将移动到下一个矩形,依此类推。
使用我制作的程序,这一切都很好,但在最后,我想打印出用户创建的所有矩形的总面积。我如何更新我的代码并实现这一点?如何存储第一个矩形的面积,并将第二个矩形的面积添加到第一个区域,依此类推?代码如下:
size = input("How many rectangles?" ) #asks the number of rectangles 
i=1
n = 1
while i <= size:
    w = input("Width "+str(n)+"? ") #asks for width of each rectangle
    h = input("Height "+str(n)+"? ") #asks for height of each rectangle
    n=n+1
    h1=1
    w1=1
    z = ""
    while w1 <= w:
        z=z+"*"
        w1+=1
    while h1<=h:
        print z
        h1+=1
    i+=1发布于 2016-10-09 00:56:11
你把总面积累加怎么样?
在您的循环之上,执行以下操作:
area = 0然后,在您的循环中的某个地方,在从用户获得w和h之后,只需这样做
area += w * h当您完成循环时,area将包含总面积。
发布于 2016-10-09 01:06:01
这段代码实际上应该使用for循环而不是while循环来跟踪计数器,将数字保存在变量中而不仅仅是"*“字符串,并且在一些地方使用+=而不是x=x+1,等等,但这里是解决您特别询问的总面积问题的最小步骤:
size = input("How many rectangles?" ) #asks the number of rectangles 
i=1
n = 1
area = 0
while i <= int(size):
    w = float(input("Width "+str(n)+"? ")) #asks for width of each rectangle
    h = float(input("Height "+str(n)+"? ")) #asks for height of each rectangle
    n+=1
    h1=1
    w1=1
    z = ""
    while w1 <= w:
        z=z+"*"
        w1+=1
    while h1<=h:
        print(z)
        h1+=1
        area += len(z)
    i+=1
print('total area = ',area)https://stackoverflow.com/questions/39934898
复制相似问题