【发布时间】:2019-03-27 22:32:22
【问题描述】:
执行时,我的代码给出退出状态 -1。如果有任何不同,我可以显示输入。有人能找到为什么会这样吗?
输入:
6
N 10
E 2
S 3
W 4
S 5
E 8
我已经查看了二维整数数组和代码中的变量,寻找未初始化的变量,但没有发现此类错误。任何人都可以看到为什么我的退出状态为 -1 吗?
#include <iostream>
#include <algorithm>
#include <fstream>
using namespace std;
int main() {
ofstream fout("mowing.out");
ifstream fin("mowing.in");
int n; fin >> n;
int ans = 0;
int field[2003][2003];
for (int i = 0; i < 2003; i++) {
for (int j = 0; j < 2003; j++) {
field[i][j] = 0;
}
}
int xloc = 1001, yloc = 1001, time = 0;
for (int i = 0; i < n; i++) {
char dir; int steps;
fin >> dir >> steps;
if (dir == 'N') {
for (int j = 1; j < steps; j++) {
yloc++;
time++;
if (field[xloc][yloc] != 0) ans = max(ans, time-field[xloc][yloc]);
field[xloc][yloc] = time;
}
}
if (dir == 'S') {
for (int j = 1; j < steps; j++) {
yloc--;
time++;
if (field[xloc][yloc] != 0) ans = max(ans, time-field[xloc][yloc]);
field[xloc][yloc] = time;
}
}
if (dir == 'W') {
for (int j = 1; j < steps; j++) {
xloc--;
time++;
if (field[xloc][yloc] != 0) ans = max(ans, time-field[xloc][yloc]);
field[xloc][yloc] = time;
}
}
else {
for (int j = 1; j < steps; j++) {
xloc++;
time++;
if (field[xloc][yloc] != 0) ans = max(ans, time-field[xloc][yloc]);
field[xloc][yloc] = time;
}
}
}
if (ans == 0) fout << -1 << "\n";
else fout << ans << "\n";
return 0;
}
【问题讨论】:
-
为自己保存几个
for循环:int field[2003][2003] = {0};会将数组的第一个元素初始化为 0,因为这是我们要求的,其余为 0,因为如果你不这样做,这是默认值'不指定一个值。 -
你的代码有几个问题,看我的回答
标签: c++ c++11 exitstatus