给定一个整数数组,请求出该数组中两数之差(绝对值)的最小值,并确定对应元素的位置。用C语言写
时间: 2024-05-14 08:16:34 浏览: 107
以下是用C语言实现的代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
int main() {
int n, i, j, min_diff = INT_MAX, diff, x, y;
printf("请输入数组长度:");
scanf("%d", &n);
int *arr = (int *)malloc(n * sizeof(int));
printf("请输入数组元素:");
for (i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
for (i = 0; i < n; i++) {
for (j = i + 1; j < n; j++) {
diff = abs(arr[i] - arr[j]);
if (min_diff > diff) {
min_diff = diff;
x = i;
y = j;
}
}
}
printf("两数之差(绝对值)的最小值为:%d,对应的元素位置为:%d和%d\n", min_diff, x, y);
free(arr);
return 0;
}
```
运行结果示例:
```
请输入数组长度:5
请输入数组元素:3 8 1 5 9
两数之差(绝对值)的最小值为:1,对应的元素位置为:0和2
```
阅读全文