【发布时间】:2020-06-09 08:10:34
【问题描述】:
我在数组和循环相关的问题上遇到了很长时间的麻烦。
假设一个数组如下:
int arr[] = {2, 3, 5, 3, 6, 8, 10, 1, 9};
程序应该打印expected 列,如图所示(注意该表是为了澄清我真正想要实现的目标):
max: expected arr[index] for max
------------------------------------
2 : 3 5 value of: arr[0]
3 : 6, 8, 10 value of: arr[3]
1 : 9 value of: arr[7]
这是我迄今为止尝试过的:
#include <iostream>
int main(void) {
int arr[] = {2, 3, 5, 3, 6, 8, 10, 1, 9};
int max = arr[0];
int i = 1, it = i;
for (; i <= max; i++) {
if (i == max) {
std::cout << arr[i] << std::endl;
max = arr[it + 1]; // when loop end has come, increment max to next element value
it = i + 2; // incrementing iterator by 2 next element position (after max)
} else {
std::cout << arr[i] << ' '; // when loop is executing
}
}
return 0;
}
它实际打印的出乎意料 V/S 它应该打印什么:
3 5 | 3, 5
3 6 8 | 6, 8, 10
10 1 9 | 1, 9
10 | <nothing>
程序即将获取最大值并打印下一个元素,直到max值达到元素位置的数量。
问题出在哪里以及如何解决?请告诉我。
【问题讨论】:
-
你把键和值放在同一个锅里……这是破解代码的完美秘诀……