以下代码用于查找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)不应该有任何问题,只进行单位数计算。那么,问题出在哪里?
答案 0 :(得分:1)
尝试在调试器中运行它。而且,你设置
int power[n][digit];
但你的循环确实
for(int iii=0;iii<=n;++iii)
当iii = n时索引越界。