【问题标题】:How to Return two integer如何返回两个整数
【发布时间】:2014-12-29 10:37:18
【问题描述】:

在这个简单的程序中我不能返回 2 个整数值,你能帮帮我吗? 我能怎么做 ?

public class Aritmetica 
{

public static int div(int x , int y)

  { 

    int q = 0 ;
    int r = x ; 
    while ( r >= y ) 
    {
      r = r - y ;  
      q = q + 1 ;  

    }
    return r && q; **// Here i want to return x and y**
 }

public static void main(String[ ] args)
 {

 if ( ( x <=0 ) & ( y > 0 ) )

  throw new IllegalArgumentException ( " X & Y must be >0  " ) ;

  int res4= div(x,y);

  System.out.println( " q and r : "+ res4) ; **// and here i want to display q and r** 

}

}

【问题讨论】:

    标签: java integer return


    【解决方案1】:

    创建结果类型:DivisionResult,如下:

    class DivisionResult {
        public final int quotient;
        public final int remaineder;
        public DivisionResult(int quotient, int remainder) {
            this.quotient = quotient;
            this.remainder = remainder;
        }
    }
    

    然后做

        ...
        return new DivisionResult(q, r);
    }
    

    并打印结果:

      DivisionResult res4= div(x,y);
    
      System.out.println("q and r: " + res4.quotient + ", " + res4.remainder);
    

    【讨论】:

      【解决方案2】:

      您可以为每个操作编写单独的方法,而不是一次返回两个整数。例如:

      public static int div1(int x , int y) { 
      
      // i replaced r with x for readibility
         while ( x >= y ) {
             x = x - y ;  
         }
         return x; // this is your variable r
      }
      
      public static int div2(int x, int y) {
          int q = 0;
          int r = x;
          while ( r >= y ) {
              r = r - y ;  // r is required here because it is your update statement in while loop
              q = q + 1 ;  
          }
          return q;
      }
      

      在您的 main 方法中,您只需调用每个方法(div1 和 div2 分别获取变量 r 和 q)。然后,您可以使用如下语句打印它们:

      System.out.println( " q and r : "+ div2(x,y) + " and " + div1(x,y)) ;
      

      我希望这很容易理解。祝你好运!

      【讨论】:

      • 非常感谢!有用 !而且很简单,因为我开始学习 java 2 周,而且我很菜鸟 ;)
      【解决方案3】:

      使用整数数组返回多个整数。

      喜欢:

      public int[] method() {  
          int[] a = {1,2,3,4,5};  
          return a;   
      }  
      

      【讨论】:

      • 在学校我们还没学过数组,所以我学不会
      • 我认为这不是一个好习惯。 result[1] 的可读性不如 result.remainder
      • @aioobe 那结果呢[REMAINDER]
      • @VikasVerma,几乎更糟。 REMAINDER 可能与包含实际余数的变量混淆。 REMAINDER_INDEX 稍微好一点,但仍然比创建 DivisionResult 类并执行 result.remainder 差很多。
      【解决方案4】:

      假设q和r小于p(可以是任何大于q和r的整数)

      现在就这样做

      return result=q*p+r

      现在,当您要打印结果时,在 main 中

      print q=result/p
      r=result-p*q
      

      【讨论】:

      • 这可能不是最佳实践,但它很有趣 :)
      • 我只需要使用 + 和 - 来进行除法,但无论如何,它似乎有效;)
      • Ya.. 这是模运算的用法。为什么不能使用乘法和除法。是拼图还是编程练习。如果您提供不同的解决方案,我相信他们会喜欢
      • 因为我必须编写一些使用 Peano 公理的程序
      猜你喜欢
      • 1970-01-01
      • 2019-10-21
      • 1970-01-01
      • 1970-01-01
      • 2016-01-15
      • 1970-01-01
      • 2011-01-01
      • 2022-01-16
      • 2021-08-16
      相关资源
      最近更新 更多