在我的程序中,我需要生成具有从 1 到 100,000 的数字的幂(从 0 到 5)总和的数组。
所以我尝试编译这段代码:
const enum size_t MAX_ARRAY_SIZE = 100_000 + 1;
const enum size_t MAX_POWER_SIZE = 5 + 1;
const enum power_sum = calc_power_sum();
// some unimportant code here
pure ulong[MAX_POWER_SIZE][MAX_ARRAY_SIZE] calc_power_sum() {
ulong[MAX_POWER_SIZE][MAX_ARRAY_SIZE] power_sum;
power_sum[0][] = 1;
foreach (x, ref element; power_sum[1]) {
element = x;
}
foreach (n; 2 .. MAX_POWER_SIZE) {
foreach (x, ref element; power_sum[n]) {
element = power_sum[n - 1][x] * power_sum[1][x];
}
}
foreach (ref power; power_sum) {
foreach (x; 1 .. MAX_ARRAY_SIZE) {
power[x] += power[x - 1]; // error appears here
}
}
return power_sum;
}
但是编译器说:
$ dmd problem.d
problem.d(130): Error: array index 6 is out of bounds [1LU, 2LU, 3LU, 4LU, 5LU, 6LU][0 .. 6]
problem.d(15): called from here: calc_power_sum()
我究竟做错了什么?