我的职能
int numSteepSegments(const int heights[], int arrSize) {
int mile = 0, steep_count = 0;
while (mile <= arrSize) {
int height = heights[mile];
int height_next = heights[mile + 1];
if ((height + 1000) < height_next) {
++steep_count;
} else if ((height - 1000) > height_next) {
++steep_count;
}
cout << heights[mile] << endl;
cout << steep_count << endl;
++mile;
}
return steep_count;
}吐出的steep_count数量是预期的两倍。
使用数组:1200, 1650, 3450, 2800, 2900, 1650, 1140, 1650, 1200和arrSize = 9,我遗漏了什么?
cout的是:
1200
0
1650
1
3450
1
2800
1
2900
2
1650
2
1140
2
1650
2
1200
3
1746942513
4最后的价值是多少?它显然不在数组中,而且我看不出它属于我处理的数字附近的任何地方。在我的条件词中,我没有看到什么会导致steep_count的错误增量
发布于 2022-02-24 00:11:28
C/C++数组是基于零的。具有arrSize元素的数组的索引范围从0到arrSize-1。
循环索引mile的范围从0到arrSize (包括在内),因此heights[mile]正在离开数组的末尾。此外,您正在索引heights[mile+1],这将超过数组限制,即使您的索引仅限于arrSize-1。
试一试:
0到arrSize-2 (包括在内),或者1到arrSize-1,并使用mile-1作为第一个索引。H 218f 219https://stackoverflow.com/questions/71245464
复制相似问题