這可以被認爲是一個家庭作業問題。 這個問題是衆所周知的:「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;
}
注:我不是在尋找的解決方案,只是一個很好的方式來處理溢出的例子不勝感激!
你的陣列仍然被定義爲短... – 2011-05-23 18:31:24
是,'int'將導致錯誤 – Buster 2011-05-23 18:31:46
有你在調試器中查了一下,當它擊中的陣列和陣列是程序正在做定義爲int類型? – 2011-05-23 18:34:31