【问题标题】:simple program without using "if condition"?不使用“if 条件”的简单程序?
【发布时间】:2013-11-05 17:30:33
【问题描述】:

有没有办法创建一个简单的java(或c,c ++,python)程序,当给定输入= 6时打印3(输出3),当给定输入= 3时输出= 6而不使用“如果条件”?

【问题讨论】:

  • 使用开关而不是如果可能?为什么不使用 if tho? (或三元运算符,如果只有两种可能性)。

标签: if-statement logic logical-operators


【解决方案1】:

假设您很高兴它在不是 6 或 3 的输入上产生其他输出,那么您只需计算 9-x。

【讨论】:

    【解决方案2】:

    您总是可以只使用 switch-case 语句。此外,如果您只想要这两个答案,您也可以将输入作为 int 并执行 9-[your int] 并打印该答案。

    【讨论】:

      【解决方案3】:

      您可以使用 XOR 位操作。它比较位对,如果位相等则返回 0,如果位不同则返回 1。
      我们有3 = 011b6 = 110b。此数字相差 1 位和 3 位(位),因此 XOR 掩码将为 101b = 5。 代码示例:

      public static int testMethod(int value){
          return System.out.println(value ^ 5);
       }
      

      【讨论】:

        【解决方案4】:

        没有if或没有控制流语句/条件语句? 你可以使用 switch 语句

        private void tes(int i) {
            switch (i) {
                ///give output 6 where input is 3
                case 3:
                    System.out.println(6);
                    break;
                ///give output 3 where input is 6
                case 6:
                    System.out.println(3);
                    break;
            }
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-11-10
          • 1970-01-01
          • 1970-01-01
          • 2019-03-18
          • 2014-05-23
          • 1970-01-01
          相关资源
          最近更新 更多