使用二维数组?

时间:2015-05-22 01:15:52

标签: c++ arrays

有人可以帮我写一个C程序,它添加了名为Array1和Array2的二维数组的等效元素吗?两个数组都应该有两行三列。

Array1

10  20  30  
40  50  60  

Array2

24  36  48  
16  12  8

1 个答案:

答案 0 :(得分:1)

2-D数组在C / C ++的内存中连续表示,所以这应该有效:

template<int R, int C>
void arraySum(int sum[R][C], const int a[R][C], const int b[R][C])
{
    for (int i = 0; i < R; i++) {
        for (int j = 0; j < C; j++) {
                sum[i][j] = a[i][j] + b[i][j];
            }
    }
}

int a[2][3] = ...;
int b[2][3] = ...;
int c[2][3];
arraySum<2,3>(a, b, c);

或者,更多矩阵式C ++:

window.verify = function() {
  var phone = document.getElementById("phone").value.split("");
  var verified = "";

  for (var char in phone)
    {
       verified += parseInt(phone[char]) >= 0 ? phone[char] : "";
    }
  var len = verified.length;
  if (len != 7 && len != 10)
    {
      alert("Invalid number of digits!");
    }
  else
    {  // then format the resulting number as you see fit
      var finalNum = "";
      if (len == 10)
      {
         finalNum += verified.substring(0,3) + "-"  
         verified = verified.substring(3);
      }
      finalNum += verified.substring(0,3) + "-";
      verified = verified.substring(3);
      finalNum += verified;
      alert(""+finalNum);
    }
}

(为C中的第一个答案道歉。)