C ++二维数组

时间:2012-08-05 01:04:13

标签: winforms multidimensional-array

我在这个学校课程中遇到了一些问题。我试图利用一个二维数组,并得到一些关于“没有从int转换为int *和'> ='的错误:'int [5]'与'int'的间接级别不同”。我可以为一维数组编写它,但是对于二维的语法有困难。对于我可能缺少的东西,有人能指出我正确的方向吗?我在btnShow_CLick之后注释掉它并且它正常工作,它只是btnGroup_Click,我显然遗漏了一些东西。

感谢任何可能分享一些知识的人。

    static const int NUMROWS = 4;
    static const int NUMCOLS = 5;
    int row, col;
    Graphics^ g;
    Brush^ redBrush;
    Brush^ yellowBrush;
    Brush^ greenBrush;
    Pen^ blackPen;


private: System::Void Form1_Load(System::Object^  sender, System::EventArgs^  e) {
             g = panel1->CreateGraphics();
             redBrush = gcnew SolidBrush(Color::Red);
             yellowBrush = gcnew SolidBrush(Color::Yellow);
             greenBrush = gcnew SolidBrush(Color::Green);
             blackPen = gcnew Pen(Color::Black);
         }

    private: System::Void btnShow_Click(System::Object^  sender, System::EventArgs^  e) {

         panel1->Refresh();

         for (int row = 0; row < NUMROWS; row++)
         {
             for (int col = 0; col < NUMCOLS; col++)
             {
                 Rectangle seat = Rectangle(75 + col * 75,40 + row *40,25,25);
                 g->DrawRectangle(blackPen, seat);
             }
         }
     }

private: System::Void btnGroup_Click(System::Object^  sender, System::EventArgs^  e) {
             int score[NUMROWS][NUMCOLS] = {{45,65,11,98,66},
                                        {56,77,78,56,56},
                                        {87,71,78,90,78},
                                        {76,75,72,79,83}};

         int mean;
         int student;
         mean = CalcMean(score[]);
         txtMean->Text = mean.ToString();

         for (int row = 0; row < NUMROWS; row++)
         {
             for (int col = 0; col < NUMCOLS; col++)
             {
                 student = (row*NUMCOLS) + (col);
                 Rectangle seat = Rectangle(75 + col * 75,40 + (row * 40),25,25);
                 if (score[student] >= 80
                     g->FillRectangle(greenBrush, seat);
                 else if (score[student] >= mean)
                     g->FillRectangle(yellowBrush, seat);
                 else 
                     g->FillRectangle(yellowBrush, seat);
                 g->DrawRectangle(blackPen, seat);
             }
         }
     }

     private: double CalcMean(int score[])
     {
         int sum = 0;
         int students = NUMROWS * NUMCOLS;
         for (int i=0; i< students; i++) sum += score[i];
         return sum / students;
     }

1 个答案:

答案 0 :(得分:1)

Score[student]相当于*(score+student),即*int。相反,您应该使用score[row][col]或其等效的**(score+student)(我强烈建议使用数组表示法)。它也相当于*Score[student],但这非常难看。

另外,当我说“它相当于”时,它只是因为sizeof int ==sizeof (*int)。如果在阵列中使用指针逻辑与另一种类型,则可能会产生质朴的结果。