例如,一个学习小组有5个人,每个人有3门课的成绩,如果使用一维数组比较麻烦;这时可以使用二维数组;
如定义一个二维数组,int a[3][4];其元素分布如下;
5个学生,每人有3门课的成绩;
#include <iostream>
using namespace std;
int main ()
{
int a[5][3] = { {60,70,90}, {13,24,55}, {82,94,77}, {30,60,90},
{74,88,90}};
// 输出数组中每个元素的值
for ( int i = 0; i < 5; i++ )
for ( int j = 0; j < 3; j++ )
{
cout << "a[" << i << "][" << j << "]: ";
cout << a[i][j]<< endl;
}
return 0;
}
MFC版本;
void CTwoarrView::OnDraw(CDC* pDC)
{
CTwoarrDoc* pDoc = GetDocument();
ASSERT_VALID(pDoc);
// TODO: add draw code for native data here
int a[5][3] = { {60,70,90}, {13,24,55}, {82,94,77}, {30,60,90},
{74,88,90}};
CString str1;
// 输出数组中每个元素的值
for ( int i = 0; i < 5; i++ )
for ( int j = 0; j < 3; j++ )
{
str1.Format("%d", a[i][j]);
pDC->TextOut(50+50*j,10+30*i,str1);
}
}