【问题标题】:Output of Python CodePython代码的输出
【发布时间】:2012-01-11 14:51:51
【问题描述】:

我是 python 新手。这是我的 wiered 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

【问题讨论】:

  • 代码应该做什么?
  • 请修正缩进。我们不知道while 循环在哪里结束。

标签: python input python-3.x


【解决方案1】:

你自己解决了这个谜(有点):

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

r 是一个字符串。所以r 永远是!=2 因为"2" != 2 永远是真的。所有其他比较也是如此。

我猜你首先得到了一个TypeErrorif r%2==0,所以你改变了程序的那个部分(也在所有其他你实际使用值进行计算的地方)但忽略了应用这个深入了解程序的其他部分。

所以首先将所有输入转换为ints,然后开始应用程序逻辑。

【讨论】:

  • 检查输出 r=100 和 c =0 ,它给出的是 25 而不是 50
  • 好的先生,非常感谢您,当我开始将 r 和 c 转换为 int 时,它正在工作。
猜你喜欢
  • 2016-06-27
  • 1970-01-01
  • 1970-01-01
  • 2019-01-12
  • 1970-01-01
  • 2012-11-27
  • 1970-01-01
  • 2020-12-07
  • 1970-01-01
相关资源
最近更新 更多