比较两个数组并返回一个整数数组,这些值是比较结果

时间:2018-12-30 13:36:45

标签: c# arrays

My not woring version编写一种方法,该方法采用两个相同长度的整数数组。方法应返回一个整数数组,其值是使用以下规则比较输入数组的结果:

a[i] > b[i], then 1
a[i] == b[i], then 0
a[i] < b[i], then -1

可能的方法签名:

static int[] CompareArrays(int[] a, int[] b) { ... }

样本输入:

a = [1, 3, 9]

b = [-2, 6, 9]

预期输出:

[1, -1, 0]

使用for循环迭代两个输入数组并将值分配给输出数组。

1 个答案:

答案 0 :(得分:0)

看起来像是家庭作业,但下面的内容应该可以帮助您开始...

static int[] CompareArrays(int[] a, int[] b) {
  //add checks to make sure a.Length == b.Length;

  //allocate space for output array
  int[] retVal = new int[a.Length];

  //iterate through all the items in the input arrays... checking length of any one of the input arrays is just fine since we assume both should be same length
  for(int i = 0; i < a.Length; ++i) {
    retVal[i] = 0;

    //add your rules here e.g. a[i] > b[i] then 1 etc
    if(a[i] > b[i]) {
      retVal[i] = 1;
    }
  }

  return retVal;
}