int A[5] = {2, 2, 1, 4, 1};
int max = A[0], min = A[0];
int k,l;
for (i = 0; i < 5; i++) {
if (A[i] >= max) {
max = A[i];
k = i;
}
}
for (j = 0; j < 5; j++) {
if (A[j] <= min) {
min = A[j];
l = j;
}
}
printf("densely is: %d ", k);
printf("\n");
printf("loosely is: %d ", l);
程序将densely
(max
)的位置打印为3
。
它将松散
(min
) 的位置打印为4
。
但松散
(min
)位置的正确答案应该是2
和4
。
就我而言,max
数字为 4
,因此位置应为 3
(从 0
开始计数)。
min
数字为 1
,因此位置应为 2
和 4
。
现在,我的代码仅显示 min
数字的一个位置:4
。
它应该打印两个位置:2
和 4
。
我想打印出 max
和 min
数字的所有位置。
最佳答案
这实际上是一个非常好的问题。解决的关键是找到min
和max
数组中的值 A
。该部分已经完成并且运行良好。这里唯一的改进是从索引 1
开始并删除 =
来自>=
和<=
比较。
缺少的部分是记住 min
的所有索引和max
.
这很难一次性完成。您可以一次性找到 min
和max
。
一旦你有min
和max
在第二遍中,您可以标记 max
的所有索引位置和min
在名为 maximums
的附加索引表中和minimums
。 (因为我想打印这些值,所以我有两个单独的循环。)
解决方案非常简单:
#include <stdio.h>
// Find all minimums and all maximums in the array A
// Find and remember where `max` and `min` values were in the array A
// The algorithm is symmetrical for minimum and maximum
int main(void)
{ // 0 1 2 3 4
int A[5] = { 2, 2, 1, 4, 1};
int maximums[5] = {0}; // we keep max positions here
int minimums[5] = {0}; // we keep min positions here
int max = A[0]; // we assume max at index 0
int min = A[0]; // we assume min at index 0
for (int i = 1; i < 5; i++) { // we can start from index 1 because of the above assumption
if (A[i] > max) max = A[i]; // densely
if (A[i] < min) min = A[i]; // loosely
}
// Find the all elements equal to `max` and `min`
// and register them in `maximums` and `minimums` arrays
// Print the results:
printf("max value is: %d and it occurs at the following index(es):\n", max);
for (int i = 0; i < 5; i++) {
if (A[i] == max){
maximums[i] = 1; // mark this index as maximum being here
printf("%d ", i);
}
}
printf("\nmin value is: %d and it occurs at the following index(es):\n", min );
for (int i = 0; i < 5; i++) {
if (A[i] == min){
minimums[i] = 1; // mark this index as minimum being here
printf("%d ", i);
}
}
// At this moment we not only printed the results
// but the array minimums and maximums remember where the `min` and `max` were.
return 0;
}
输出:
max value is: 4 and it occurs at the following index(es):
3
min value is: 1 and it occurs at the following index(es):
2 4
关于c - 如何找到数组中最大和最小数字的位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49347642/