【问题标题】:FizzBuzz program never satisfies one of the conditionsFizzBu​​zz 程序从不满足条件之一
【发布时间】:2019-07-04 07:37:51
【问题描述】:

编写一个 Python 程序,为给定的数字显示如下消息:

如果是三的倍数,则显示“Zip” 如果是五的倍数,则显示“Zap”。 如果是三和五的倍数,则显示“缩放”。 如果不满足上述任一条件,则显示“无效”。

def display(num):
    message="Zip, Zap, Zoom"

    if(num%3==0):
      print("Zip")
    elif(num%5==0):
      print("Zap")
    elif((num%3==0) and (num%5==0)):
      print("Zoom")
    else:
      print("Invalid Number")
    return message


message=display(15)
print(message)

我希望 15 的输出是 Zoom,但实际输出的是 Zip。

【问题讨论】:

    标签: python if-statement modulus fizzbuzz


    【解决方案1】:

    你需要重新排序你的 if...elif...else 语句

    如果 if 的条件为 False,则检查下一个 elif 块的条件,依此类推,但如果其中一个语句为真,则执行该语句的主体并退出。

    如果所有条件都为 False,则执行 else 的主体。

    def display(num):
    
        if((num%3==0) and (num%5==0)):
            message = "Zoom"
        elif(num%3==0):
            message = "Zip"
        elif(num%5==0):
            message = "Zap"
        else:
          print("Invalid Number")
        return message
    
    
    message=display(3)
    print(message)
    

    【讨论】:

      【解决方案2】:

      这是因为 15 是 3 的倍数并且满足第一个条件,所以输出为“Zip”。你可以简单地修复它:

      if(num%3==0 and num%5!=0):
        print("Zip")
      elif(num%5==0 and num%3!=0):
        print("Zap")
      elif((num%3==0) and (num%5==0)):
        print("Zoom")
      else:
        print("Invalid Number")
      return message
      

      【讨论】:

        【解决方案3】:

        替代方案:[从用户那里获取价值。希望对您有所帮助!]

        num=int(input("Enter the value : "))
        
        if(num % 5 == 0):
            if(num % 3 == 0):
                print("Zoom")
            else:
                 print("Zap") 
        elif(num % 3 == 0):
             print("Zip")
        else:
             print("invalid")
        

        【讨论】:

          【解决方案4】:

          Java 解决方案

          实现一个程序,根据以下条件显示给定号码的消息。 如果数字是 3 的倍数,则显示“Zip”。 如果数字是 5 的倍数,则显示“Zap”。 如果数字是 3 和 5 的倍数,则显示“缩放”, 对于所有其他情况,显示“无效”。

          class ZipZapZoom 
          {
              public static void main(String[] args) 
              {
                  // Implement your code here 
                  int num = 10;
                  if(num % 3==0 & num %5 == 0)
                  {
                      System.out.println("Zoom");
                      
                  }
                  else if(num % 5 == 0)
                  {
                      System.out.println("Zap");
                  }
                  else if(num % 3==0)
                  {
                      System.out.println("Zip");
                  }
                  else
                  {
                      System.out.println("Invalid");
                  }
              }
          }
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2012-03-16
            • 1970-01-01
            • 1970-01-01
            • 2010-09-18
            • 1970-01-01
            • 2012-02-21
            • 2018-07-18
            • 2012-11-04
            相关资源
            最近更新 更多