c - 怎么了?运行 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;
}
解决方案
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
推荐阅读
- google-sheets - 我可以缩短这个公式并使其更快吗?
- php - 在任何页面中显示产品数量或通过简码发布
- javascript - ESLint 规则仅允许每个文件的默认或命名导出
- angular - 如何在拦截器Angular中获取请求的查询参数
- c# - 从 TextBlock 样式设置多边形可见性
- node.js - 如何在我的 ejs 文件成功输出上添加 sweetalert?
- c# - 在 Asp.Net Core (MVC) 的现有项目中将身份验证从无身份验证更改为个人身份验证
- watson-discovery - 可以在 Watson Discovery 集合中创建的字段数量是否有限制
- java - Hibernate中字符串类型的外键
- r - auto.arima 函数中的 xreg 有什么用?