【问题标题】:Using an array to find the multiples of two ints使用数组查找两个整数的倍数
【发布时间】:2017-01-13 06:17:08
【问题描述】:

我是一名编程学生,我在这个问题上遇到了很多麻烦:

"完成一个静态方法multiplesOf,它接受两个int参数,number和count。方法体必须返回一个int数组,其中包含number的第一个count倍数。例如,

multiplesOf(5, 4) 应该返回数组 { 5, 10, 15, 20 } multiplesOf(11, 3) 应该返回数组 { 11, 22, 33 } multiplesOf(1, 15) 应该返回数组 { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 }

您不得在您的方法中使用 System.out.print 或 System.out.println。”

这是我当前的代码:

public static void main(String[] args) {
    multiplesOf(5,4);
}

public static int[] multiplesOf (int number, int count) {
    int[] a = new int[count];
    a[0]= number;
    for(int i = 0; i<count; i++) {
        a[i] = (a[i]*count);
    }
    return a;
}

我一直试图弄清楚为什么数组“a”仍然只有值 0,1,2,3

【问题讨论】:

  • a[i] = (a[i]*count); 是做什么的?

标签: java arrays


【解决方案1】:

试试:

public static int[] multiplesOf(int number, int count) {
  int[] a = new int[count];
  for(int i = 1; i <= count; i++) {
    a[i - 1] = number * i;
  }
  return a;
}

【讨论】:

    【解决方案2】:
    a[0] = number;
    for(int i = 1; i<count; i++)
    {
          a[i] = (i+1)*number;
    }
    

    【讨论】:

    • 啊,是的,你的速度更快 :D 但我认为当我看到所有错误的答案时,我可以让答案留在这里 :) 我会支持你
    • 真的很震撼
    【解决方案3】:

    试试这个

            public static int[] multiplesOf (int number, int count)
            {
                int[] a = new int[count];
                a[0] = number;
                for(int i = 1; i<count; i++)
                {
                  a[i] = number * (i + 1);
                }
                return a;
              }
    

    输出

    [5, 10, 15, 20]

    【讨论】:

      【解决方案4】:
          public static int[] multiplesOf(int number, int count) {
          int[] a = new int[count];
          for (int i = 0; i < count; i++) {
              a[i] = (number * (i+1));
          }
          return a;
      }
      

      使用这个

      【讨论】:

      • 正如 OP 所说“你不能在你的方法中使用 System.out.print 或 System.out.println。”
      • 不得在您的方法中使用 System.out.print 或 System.out.println。
      • 不需要SOP;该数组应该只是返回,而不是打印。
      • 我只是通过打印检查..现在进行了更改。
      • 然后发布你的输出
      【解决方案5】:
       public static int[] multiplesOf (int number, int count) {
           int[] a = new int[count];
           for(int i = 1; i<=count; i++) {
               //a[i-1] beacuse we started iterating array at i=1
               a[i-1] = (i*number); 
           }
           return a;
      }
      

      multiplesOf(5, 4) 返回 -> 数组 { 5, 10, 15, 20 }

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-01-07
        • 1970-01-01
        • 1970-01-01
        • 2014-05-22
        • 1970-01-01
        • 2017-06-18
        • 1970-01-01
        • 2021-11-14
        相关资源
        最近更新 更多