【发布时间】:2017-05-18 19:42:46
【问题描述】:
我编写了以下代码,但它生成了荒谬的输出值。我无法弄清楚代码中有什么问题。
#include <stdio.h>
int main(void)
{
int t, n, i, count;
scanf("%d", &t);
while(t--)
{
scanf("%d", &n);
long long a[n], limit;
for(i = 1; i <= n; i++)
scanf("%lld", &a[i]);
count = 1;
limit = a[1];
for(i = 2; i <= n; i++)
{
if(a[i] < limit)
{
count++;
limit = a[i];
}
}
printf("%lld\n", count);
}
return 0;
}
输入:-
3
1
10
3
8 3 6
5
4 5 1 2 3
输出:-
-4621320042389176319
4615368115365085186
-4621320334446952446
请解释我的代码有什么问题。
【问题讨论】:
-
for循环的范围(以及循环内的索引)都是错误的。您正在访问超出数组a的范围。数组索引范围为0... N-1。