在我的代码中,我仅分别扫描t,n和m的值。调试时,我发现无论我给m的值是什么,它都取值0。您可以为输入运行以下代码:
1
3 4
此处,输出应为4,但意外地为0。 另一方面,当我在for循环之后扫描n和m的值时,输出将达到预期的效果(即本例中为4)。我已注释掉该行,以便您可以弄清为什么会发生这种情况。
#include <bits/stdc++.h>
using namespace std;
int main()
{
long long t,n,m,i,j;
scanf("%lld",&t); // Scan t (of no use)
while(t--){
scanf("%lld %lld",&n,&m); // If I scan n and m here, the
//output is always 0
long long x[9000],y[9000],ans[9000],in=0;
for(i=1;i<=9000;i++){
ans[i]=0;
x[i]=0;
y[i]=0;
}
//scanf("%lld %lld",&n,&m);//Output is correct if I scan the values here
cout<< m << endl;
}
}
答案 0 :(得分:2)
当i = 9000
时,您将在以下语句中最终访问越界内存。这导致undefined的行为。
ans[i]=0;
x[i]=0;
y[i]=0;
答案 1 :(得分:1)
经典的“ off by one”错误。 将您的for循环更改为:
for(i=0;i<9000;++i){
ans[i]=0;
x[i]=0;
y[i]=0;
}