首页 > 解决方案 > 怎么了?运行 C 代码时出现运行时错误

问题描述

当我编译此代码时,我无法找出为什么会出现运行时错误。有人能告诉我我的代码有什么问题吗?

#include <stdio.h>
int main(void)
{
    int ai[100], n=0, m=0, test=0, count=0;
    scanf("%d", &n);
    scanf("%d", &m);
    for(int i=0;i<n;i++)
    {
        scanf("%d", &ai[i]);
    }
    for(int j=0;j<n;j++)
    {
        test = ai[j]+ai[j+1];
        if(test<=m)
        {
            count++;
        } else
        {
            j=j-1;
            count++;
        }
    }
    printf("%d", count);
    return 0;
}

标签: c

解决方案


for(int j=0;j<n;j++)
    {
        test = ai[j]+ai[j+1];
        if(test<=m)
        {
            count++;
        } else
        {
            j=j-1;
            count++;
        }
    }

注意:

  • j=j-1;可以将 j 设为负值 =>运行时错误。
  • 当 j = n -1, test = ai[j]+ai[j+1];=> aj[j+1] <=> ai[n] 时,索引应该是 <= n - 1

推荐阅读