2012-08-05 243 views
0

我在學校的這個程序中遇到了一些問題。我試圖利用一個二維數組,並得到一些關於「從int到int *和'> ='的轉換錯誤:'int [5]'與'int''的間接級別不同。我可以把它寫成一維數組,但是對於二維的語法有困難。有人能指出我在正確的方向關於我可能錯過的東西嗎?我在btnShow_CLick之後註釋掉了,它工作正常,它只是btnGroup_Click,我明顯錯過了某些東西。C++二維數組

感謝任何可能分享一些知識的人。

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

Score[student]相當於*(score+student),這是一個*int。相反,您應該使用score[row][col]或其等效的**(score+student)(我強烈建議數組表示法)。它也相當於*Score[student],但這很醜陋。

加上當我說「它是等價的」時,它只是因爲sizeof int ==sizeof (*int)。如果你在數組中使用另一種類型的指針邏輯,你可能會得到時髦的結果。

+0

非常感謝! – user1576776 2012-08-05 01:59:37