2016-08-12 109 views
0

我正在編寫一個代碼來創建一個值,並創建一個大小爲1s的金字塔的矩陣,因此頂部是x-1元素。例如,如果輸入是五,則輸出將是:C++中的矩陣輸出不正確

0 0 0 0 1 0 0 0 0 
0 0 0 1 0 1 0 0 0 
0 0 1 0 0 0 1 0 0 
0 1 0 0 0 0 0 1 0 
1 0 0 0 0 0 0 0 1 

問題是代碼生成的值,不應該是一個,或它是不輸出矩陣的正確方法。我試圖在代碼中添加一個cout,它將一些值定義爲1,這些值都是正確的,所以我相信問題出在輸出中。例如,x的輸入會給

0 0 0 0 1 0 0 0 1 
0 0 0 1 0 1 0 1 0 
1 0 1 0 0 0 1 0 0 
0 1 0 0 0 1 0 1 0 
1 0 1 0 0 0 0 0 1 

的代碼如下:

#include <iostream> 
using namespace std; 

int main() { 
     cout << "Matrix size:"; 
     int x; 
     cin >> x; 
     int arr1[2*x][x]; 
     for (int initialX=0; initialX<x; initialX++){ 
       for (int initialY=0; initialY<=((2*x)-2); initialY++){ 
         arr1[initialX][initialY]=0; 
       } 
     } 
     for (int set=0; set<x; set++){ 
       arr1[set][x-1-set]=1; 
       arr1[set][x-1+set]=1; 
     } 
     for (int outX=0; outX<x; outX++){ 
       for (int outY=0; outY<(2*x-1); outY++){ 
         cout << arr1[outX][outY] << " "; 
       } 
       cout << endl; 
     } 
     return 0; 
} 

這與矩陣工作在C我第一次++,因此關於矩陣任何幫助表示讚賞。另外,如果它非常重要,我正在使用C++ 11。先謝謝你。

+5

VLAs是非標準的C++,即使它們在您的編譯器中工作,您也應該避免使用它們。 – ArchbishopOfBanterbury

+0

歡迎來到Stack Overflow!這聽起來像你可能需要學習如何使用調試器來遍歷代碼。使用一個好的調試器,您可以逐行執行您的程序,並查看它與您期望的偏離的位置。如果你打算做任何編程,這是一個重要的工具。進一步閱讀:[如何調試小程序](http://ericlippert.com/2014/03/05/how-to-debug-small-programs/)。 –

+1

請看看這個爲什麼你[不應該使用可變長度數組](http://ideone.com/1mcWo6)。使用'std :: vector'和'at()'清楚地說明了問題所在。使用VLA的人員的帖子數量很多,並且出現了分段錯誤或輸出錯誤的問題,如果VLA的使用已停止,並且使用了「矢量」(與另外的vector :: at ()'call)。 – PaulMcKenzie

回答

1

需要切換陣列尺寸。取而代之的

int arr1[2*x][x]; 

使用

int arr1[x][2*x]; 

因爲這個錯誤,你正在訪問數組越界,這會導致不確定的行爲。

由於VLA不是標準C++,我強烈推薦使用std::vector

std::vector<std::vector<int>> arr1(x, std::vector<int>(2*x)); 

這也將所有元素初始化爲0,並避免了需要編寫顯式代碼數組元素初始化爲0

0

我想你可能已經交換了你的設置的索引值。另外,我不建議使用set作爲變量名稱。試試這個:

for (int i=0; i<x; i++){ 
    arr1[x-1-i][x]=1; 
    arr1[x-1+i][x]=1; 
} 

如果有疑問,試着用小的值來代碼,比如x = 2。

0
#include <iostream> 
using namespace std; 

int** CreateMatrix(int size); 

int main() 
{ 
    cout << "Matrix size:"; 
    int x; 
    cin >> x; 

    int** intArray = CreateMatrix(x); 

    int max = (x * 2) - 1; 

    for (int row = 0; row < x; row++) 
    { 
     for (int col = 0; col < max; col++) 
     { 
      cout << intArray[row][col] << " "; 
     } 
     cout << endl; 
    } 
    return 0; 
} 

int** CreateMatrix(int size) 
{ 
    int max = (size * 2) -1; 
    int** intArray = new int*[size]; 
    for (int index = 0; index < size; index++) 
     intArray[index] = new int[max]; 

    int middle = size - 1; 
    int low = middle; 
    int high = middle; 

    for (int row = 0; row < size; row++) 
    { 
     for (int col = 0; col < max; col++) 
     { 
      intArray[row][col] = (col == low || col == high) ? 1 : 0; 
     } 
     low--; 
     high++; 
    } 
    return intArray; 
} 
+0

此代碼存在內存泄漏,並演示了爲什麼應該使用'std :: vector'代替C++中動態分配的C風格數組的主要示例。 – ArchbishopOfBanterbury

+0

刪除很簡單。問題更多的是關於如何正確創建矩陣。(int row = 0; row