本地编译的 C++ 代码循环不正确
Locally compiled c++ code is improperly looping
以下在我的系统上永远不会终止。
#include <iostream>
using namespace std;
int main(){
int solutions[1000][4] = {};
for(int a=0; 3*a<=1000; a++){
for(int b=0; 5*b<=1000; b++){
for(int c=0; 7*c<=1000; c++){
cout << "enter" << "\t" << a << "\t" << b << "\t" << c << endl;
if (3*a+5*b+7*c > 1000) {break;}
solutions[3*a+5*b+7*c][0] = a;
solutions[3*a+5*b+7*c][1] = b;
solutions[3*a+5*b+7*c][2] = c;
solutions[3*a+5*b+7*c][3] = 1;
cout << "exit" << "\t" << a << "\t" << b << "\t" << c << endl << endl;
}
}
}
}
我完全被难住了,所以我决定打印一份变量更改日志。它使 b 的 4 次迭代,然后当 c 达到 140 时,它循环回到 0。日志看起来像这样
...
enter 0 4 137
exit 0 4 137
enter 0 4 138
exit 0 4 138
enter 0 4 139
exit 0 4 139
enter 0 4 140
exit 0 4 0
enter 0 4 1
exit 0 4 1
enter 0 4 2
exit 0 4 2
enter 0 4 3
exit 0 4 3
...
我使用 g++ B.cpp -o B.exe
编译了它,然后只是 运行 可执行文件。确切的代码(注释掉日志记录)在 http://cpp.sh/ 处正确在线终止。我的编译器版本是 g++ (i686-posix-dwarf-rev0, Built by MinGW-W64 project) 5.3.0
。这里可能出了什么问题?
当a = 0, b = 4, c = 140
时,3*a+5*b+7*c
变为1000
并发生写入越界solution[1000]
。似乎这个越界写入碰巧打破了循环计数器。
再分配一个元素以避免这种越界写入。
int solutions[1001][4] = {};
以下在我的系统上永远不会终止。
#include <iostream>
using namespace std;
int main(){
int solutions[1000][4] = {};
for(int a=0; 3*a<=1000; a++){
for(int b=0; 5*b<=1000; b++){
for(int c=0; 7*c<=1000; c++){
cout << "enter" << "\t" << a << "\t" << b << "\t" << c << endl;
if (3*a+5*b+7*c > 1000) {break;}
solutions[3*a+5*b+7*c][0] = a;
solutions[3*a+5*b+7*c][1] = b;
solutions[3*a+5*b+7*c][2] = c;
solutions[3*a+5*b+7*c][3] = 1;
cout << "exit" << "\t" << a << "\t" << b << "\t" << c << endl << endl;
}
}
}
}
我完全被难住了,所以我决定打印一份变量更改日志。它使 b 的 4 次迭代,然后当 c 达到 140 时,它循环回到 0。日志看起来像这样
...
enter 0 4 137
exit 0 4 137
enter 0 4 138
exit 0 4 138
enter 0 4 139
exit 0 4 139
enter 0 4 140
exit 0 4 0
enter 0 4 1
exit 0 4 1
enter 0 4 2
exit 0 4 2
enter 0 4 3
exit 0 4 3
...
我使用 g++ B.cpp -o B.exe
编译了它,然后只是 运行 可执行文件。确切的代码(注释掉日志记录)在 http://cpp.sh/ 处正确在线终止。我的编译器版本是 g++ (i686-posix-dwarf-rev0, Built by MinGW-W64 project) 5.3.0
。这里可能出了什么问题?
当a = 0, b = 4, c = 140
时,3*a+5*b+7*c
变为1000
并发生写入越界solution[1000]
。似乎这个越界写入碰巧打破了循环计数器。
再分配一个元素以避免这种越界写入。
int solutions[1001][4] = {};