2012-01-11 64 views
-1

我是python的新手。這裏是我的wiered Python代碼,它適用於所有輸入,除了Python代碼的輸出

當c = 0且r!= 0時。

我有一些測試用例(tc),r和c作爲輸入,它們給出了所需的輸出依賴條件。

問題---對於輸入r = 4 & c = 0,輸出應爲2,但輸出即將到來1。我爲每一個r = 0 & c = 0給出了錯誤的答案。

代碼:

tc=int(input()) 
while tc: 
    r,c=raw_input().split() 
    if int(r)%2==0 and r!=2 and r!=0 and c!=0: 
     r=int(r)/2 
    elif r!=2 and r!=0 and c!=0: 
     r=int(r)/2+1 
    elif r==0 or r ==2: 
     r=1 
    if r!=0: 
     if int(c)!=0: 
      print(int(r)*int(c)) 
     else : 
      if int(r)%2==0 : 
       print(int(r)/2) 
      else: 
       r=int(r)/2+1 
       print(r) 
    else : 
     print(c); 
    tc=tc-1 

樣品輸入和輸出

4   //tc 
10 10  //r=10 c= 10 
50  //fine 
3 3  //r=3 c=3 
6   //fine 
4 0  //r=4 c=0 
1   //Should be 2 accoring to code 
5 0  //r=5 c=0 
2  //Output should be 3 accoring to the code 
+2

代碼應該做什麼? – Kimvais 2012-01-11 14:53:23

+0

請修復您的縮進。我們無法分辨'while'循環結束的位置。 – 2012-01-11 14:53:52

回答

7

你自己已經解開了這個謎團(種):

if int(r)%2==0 and r!=2 and r!=0 and c!=0: 

r是一個字符串。因此r將始終爲!=2,因爲"2" != 2始終爲真。所有其他比較也是如此。

我猜你第一次得到TypeErrorif r%2==0,所以你改變了那一點的程序(也在所有其他地方,你實際上正在計算的值),但忽略了這個洞察應用到該計劃的其他部分。因此,首先將所有輸入轉換爲int s,然後開始應用程序邏輯。

+0

檢查輸出r = 100和c = 0,它給出25而不是50 – anil 2012-01-11 15:00:28

+0

你糾正了你的代碼嗎? – 2012-01-11 15:01:28

+0

好吧,先生,非常感謝你在開始時將r和c轉換爲int。 – anil 2012-01-11 15:03:37