用C使用循环
问题描述:
我有一个一维阵列和二维阵列的一些值添加值到2D阵列从一维数组++。我想用一个循环将一维数组的值添加到二维数组中。用C使用循环
到目前为止,我有以下代码:
#include <iostream>
#include <conio.h> //for _kbhit
using namespace std;
#define MAX_N 100
int c[MAX_N] = {21, 12, 23, 34, 15, 16};
int b[MAX_N][MAX_N] = {
{ 10 , 11 , 20 },
{ 22 , 30 , 33 },
{ 40 , 44 , 50 },
{ 55 , 60 , 66 }
};
int main()
{
int i,j,k,l;
int idx = 0;
for(i=0 ; i<2 ; i++)
{
for(j=0 ; j<3 ; j++)
{
b[i][j] = c[idx++];
}
}
for (k = 0 ; k < 2 ; k++)
{
for (l = 0 ; l < 3 ; l++)
{
cout << b[k][l] << " " ;
} cout << endl;
}
cout << "\n\nHit<enter> to finish";
while (!_kbhit());
return (0);
}
它不工作,因为我想要的。假设的输出是:
10 11 20
22 30 33
40 44 50
55 60 66
21 12 23
34 15 16
请帮忙吗? 谢谢!
答
尽量保持你添加到二维数组的每个元素的跟踪。现在你只需要创建一个新的数组不添加值
答
如前所述,你最初的for循环覆盖你的表。还有更多的代码真正增加,但在下面这段代码一般看看,看看是否有帮助:
int nextRow = 4;
int itemsToAdd = 6;
int rowsToAdd = itemsToAdd/3;
int additional = itemsToAdd%3; // just added as hint for incomplete rows
int totalRows = nextRow + rowsToAdd;
int idx = 0;
for(i=nextRow; i<totalRows ; i++)
{
for(j=0 ; j<3 ; j++)
{
b[i][j] = c[idx++];
}
}
最后,你需要更新你的输出循环中使用的totalRows变量。
它不起作用,因为这里'为(I = 0; I DimChtz