2017-09-24 132 views
0
x = int(input('Enter x: ')) 
y = int(input('Enter y: ')) 

product = 0 
## 50 in border 
border = str('-------------------------------------------------------') 
print(border) 
print('%15s' % 'x', '%15s' % 'y', '%23s' % 'product') 
print(border) 

if y < x: 
    temp = x 
    x = y 
    y = temp 
xTwo = x 
yTwo = y 

productTwo = x*y 

while not x <= 0: 

    if x % 2 == 0: 
     x = x/2 
     y = y*2 

    else: 
     x = x - 1 
     product = product + y 

    print('%15d' % x, '%15d' % y, '%23d' % int(product)) 

else: 
    print(border) 
    print(xTwo, '*', yTwo, '=', productTwo) 

**下面是它生成的內容。在循環中,我希望第一個數字行讀取'12 14 0',但我不確定在哪裏需要放置打印行以便發生,或者如果我可以稍微更改循環以產生結果****Loop不打印正確的輸出

Enter x: 12 
Enter y: 14 
------------------------------------------------------- 
      x    y     product 
------------------------------------------------------- 
      6    28      168 
      3    56      168 
      2    56      224 
      1    112      224 
      0    112      336 
------------------------------------------------------- 
12 * 14 = 168 
+0

嘗試把打印線在循環開始後右:'而不是X <= 0: 打印( '%15d的' %的x, '%15d的' %Y, '%23d的' %INT(產品))' – davedwards

回答

0

問題出在打印語句的位置。你需要把它放在while循環的第一行。如果你不這樣做,那麼x%2 = 0條件變爲真,並且x值被改變。

x = int(input('Enter x: ')) 
y = int(input('Enter y: ')) 

product = 0 
## 50 in border 
border = str('-------------------------------------------------------') 
print(border) 
print('%15s' % 'x', '%15s' % 'y', '%23s' % 'product') 
print(border) 

if y < x: 
    temp = x 
    x = y 
    y = temp 
xTwo = x 
yTwo = y 

productTwo = x*y 

while not x <= 0: 
    print('%15d' % x, '%15d' % y, '%23d' % int(product)) 

    if x % 2 == 0: 
     x = x/2 
     y = y*2 

    else: 
     x = x - 1 
     product = product + y 


else: 
    print(border) 
    print(xTwo, '*', yTwo, '=', productTwo)