2011-05-23 142 views
1

這可以被認爲是一個家庭作業問題。 這個問題是衆所周知的:「you have a triangle of numbers and you have to find the greatest sum溢出或內存錯誤C++

好吧,沒問題,我在python前段時間做了一個解決方案,作品完美無缺。 但現在在C++中,解決方案是75256,我的答案是9729. 所以問題是short類型溢出。

所以要解決這個問題,我認爲改變我的數組類型int會解決一切..但是,當聲明一個數組a[1001][1001]它凍結(我猜內存錯誤)。

有人知道該怎麼辦? 我用另一個int嘗試了一些東西,並且每當a中的值比32767大時,它就會增加,但是我的解決方案仍然是300? (代碼工作 - 測試的許多較小的)

#include <iostream> 
#include <fstream> 

int main() { 
    std::ofstream fout ("numtri.out"); 
    std::ifstream fin ("numtri.in"); 
    short trifield[1001][1001] = {0}; 
    int Rows, tmp=0; 
    fin >> Rows; 
    for (int x = 0; x<Rows;x++) 
     for (int nr = 0; nr<=x;nr++){ 
      fin >> tmp; 
      trifield[x][nr] = tmp;} 

    for (int y = (Rows-2); y > -1; y--) 
     for (int x = 0; x <= y+1; x++) { 
      int a = trifield[y+1][x]; 
      int b = trifield[y+1][x+1]; 
      if (a > b) trifield[y][x] += a; 
      else  trifield[y][x] += b; 
     } 
    fout << trifield[0][0] << std::endl; 
    return 0;  
} 

注:我不是在尋找的解決方案,只是一個很好的方式來處理溢出的例子不勝感激!

+0

你的陣列仍然被定義爲短... – 2011-05-23 18:31:24

+0

是,'int'將導致錯誤 – Buster 2011-05-23 18:31:46

+0

有你在調試器中查了一下,當它擊中的陣列和陣列是程序正在做定義爲int類型? – 2011-05-23 18:34:31

回答

1

你得到一個堆棧溢出而不是數字溢出!

將數組移動到main之外的靜態內存中,所以它不使用堆棧。

+0

非常感謝你! – Buster 2011-05-23 18:44:43

3

如果您有內存問題嘗試動態分配的數組:

short** trifield = new short[1001][1001]; 
+0

你能解釋一下嗎? – Buster 2011-05-23 18:35:34

+1

@Buster如果直接分配內存,它將在堆棧空間中完成。這個空間通常非常有限。通過動態分配,您可以訪問更多的內存。 – Howard 2011-05-23 18:37:52

+0

如果將數組移動到main之外,還可以獲得更多的內存。這裏不需要動態分配,因爲只有一個數組且其大小已知。 – 2011-05-23 18:41:02

2

你的1001x1001短褲......這就是1002001 * 2個字節數組。這一切都在你的local stack上。取決於你的系統可能太大。嘗試用malloc分配空間給你的'trifield'。看看它對你有什麼影響

+0

並記住,你應該注意什麼,你必須自由設置 – Andrew 2011-05-23 18:36:07

+3

而問題是關於C++,不要使用malloc。 – 2011-05-23 18:38:43

0

溢出int是UB。在標準中定義溢出無符號整數值。

因此,唯一的方法是在執行操作之前手動檢查這些值,並確保它不會溢出。

1

我檢查溢出的方式是檢查是否有明顯的虛假結果。例如,

if (myInt + 1 < myInt) { 
    // Overflow condition 
    cerr << "Overflow" << endl; 
} 
else { 
    myInt++; 
}