【问题标题】:how to append data in existing array element without overwriting the data in element如何在现有数组元素中追加数据而不覆盖元素中的数据
【发布时间】:2015-06-13 11:38:08
【问题描述】:

所以我有两个整数数组。我需要将它们相乘,但为此我需要将每个步骤的结果存储在一个临时数组的元素中。例如:

说数组是:

arf[2] = {1, 2};

ars[2] = {3, 2};

tmp[20]; // 每一步的临时数组

分辨率[20]; // 将每一步的结果存储在一个元素中

现在对于乘法,我们首先做 2*2 并将其存储在 tmp[1] 中, 然后 2*1 并将其存储在 tmp[0] 中, 答案是 24。现在我需要将 24 存储在 res 数组的第一个元素中。所以 res[0] = 24。3 * 12 也是如此。我知道我需要用 for 循环来做。我将 tmp[1] 存储在 res[0] 中,接下来我需要将 tmp[0] 附加到 res[0] 但它会覆盖它。

在这种情况下,c 为 2,因为 arf 和 ars 各有 2 个元素。

for (k = c - 1; k >= 0; k--)
        {
            res[i] = tmp[k];
        }

那么如何在现有元素中追加数据而不覆盖其中的数据?

【问题讨论】:

  • 你能更清楚你所说的令人困惑的事情吗?现在对于乘法,我们首先做 2*2 并将其存储在 tmp[1],然后 2*1 并将其存储在 tmp[0 ],答案是 24。”我不知道 24 岁的答案如何?
  • @Ankur Patel:OP 正在尝试实现正常乘法,其中数组将数字表示为数字列表。
  • for(k = 0; k < c; ++k) res[i] = res[i]*10 + tmp[k];
  • 2*2 = 4; 2*1=2;它是向后循环,所以它是 24。
  • 我真的需要一些帮助。

标签: c arrays append


【解决方案1】:
int myMult(int[] num1, int num1Size, int[] num2, int num2Size)
{
  //reverse the arrays so exponent work simplifies
  int newNum1[num1Size];
  for(int i = 0; i < num1Size; i++)
    newNum1[i] = num1[num1Size - 1 - i];
  int newNum2[num2Size];
  for(int i = 0; i < num1Size; i++)
    newNum2[i] = num2[num2Size - 1 - i];

  //create an array to store temporary values
  int temp[num1Size + num2size];
  for(int i = 0; i < num1Size + num2Size; i++)
    temp[i] = 0;

  //perform multiplication digit-wise
  for(int j = 0; j < num2Size; j++;)
  {
    //multiply the given digit through the first number
    for(int i = 0; i < num1Size; i++)
      //add the result to the location in temp, don't replace it
      temp[i+j] += newNum1[i] * newNum2[j];
  }

  //add up the values stored in temp
  int result = 0;
  for(int i = 0; i < num1Size + num2Size; i++)
    result += temp[i] * pow(10, i);

  return result;
}

嵌套循环的工作方式如下:

  1. 从第二个数字的个位开始(在您的示例中为 2)
  2. 将该值乘以第一个数字并将结果存储在 temp (temp[0] = 2*2 + 0 = 4, temp[1] = 2*1 + 0 = 2)
  3. 重复十位,但移到添加结果的位置(temp[1] = 3*2 + 2 = 8, temp[2] = 3*1 + 0 = 3;)

数组 temp 代表结果的每个数字。例如 temp[0] 代表个位,temp[1] 代表十位。当您将数组的值相加时,您会考虑位置值。

在您的示例中,我们有 temp[] = {4, 8, 3}; 因此,当我们通过 temp 相加时,我们得到:

4*10^0 + 8*10^1 + 3*10^2 = 4 + 80 + 300 = 384,应该是这样。

希望对你有帮助

注意:在我意识到这是 C 而不是 C++ 之前,我写下了这个答案。我的语法可能有点不对劲,但逻辑本身应该是合理的。

【讨论】:

    猜你喜欢
    • 2016-01-21
    • 2019-10-04
    • 1970-01-01
    • 1970-01-01
    • 2022-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-19
    相关资源
    最近更新 更多