以下代碼用於查找2^n。它工作正常(並給出正確的結果)n < = 1307。然而它崩潰n> 1307。我想知道問題在哪裏。代碼適用於某些點,然後崩潰
#include <iostream>
#include <cmath>
using namespace std;
const int n=1307; //digit sum of 2^n
const int digit= n*log10(2)+5; //expected no of digits in 2^n (+5 for safety)
int main()
{
int power[n][digit]; // power[n][k] is the kth digit (from right) of 2^n
for (int iii=0; iii<=n; iii++) // initialize every digit to 0
for (int jjj=0; jjj<digit; jjj++)
power[iii][jjj]=0;
power[1][0]=2; //set 2^1=2
//each step calculate 2^n by doubling 2^(n-1)
for (int iii=2; iii<=n; iii++)
{
int carry=0;
for (int jjj=0; jjj<digit; jjj++)
{
int k=2*power[iii-1][jjj]; //temp variable
power[iii][jjj]=(k+carry)%10;
carry=(k+carry)/10;
}
}
for (int jjj=digit -1; jjj>=0; jjj--)
cout << power[n][jjj];
}
不應該有任何關於類型(int,long)的問題,只有單個數字的計算正在發生。那麼,問題在哪裏?
您是否嘗試過在調試器中運行它? – 2014-10-10 10:21:12
我做了,首先它沒有問題。然後我注意到我只在n <= 1307時才跑了它。再次運行n = 1308,返回碎片錯誤。我不知道這意味着什麼。 – Rohcana 2014-10-10 11:18:16
你可能會加入堆棧。嘗試通過'malloc'或'new'分配'power' – Valerij 2014-10-10 12:45:58