编写一个程序,找出一维数组中元素的最大值,最小值及其差值
时间: 2024-02-11 11:06:52 浏览: 84
汇编程序 求数组元素的最大值和最小值
4星 · 用户满意度95%
好的,下面是 Python 代码实现:
```python
def find_max_min_diff(arr):
max_val = arr[0]
min_val = arr[0]
for i in range(1, len(arr)):
if arr[i] > max_val:
max_val = arr[i]
if arr[i] < min_val:
min_val = arr[i]
diff = max_val - min_val
return max_val, min_val, diff
# 示例用法
arr = [3, 7, 2, 1, 8, 4, 5]
max_val, min_val, diff = find_max_min_diff(arr)
print("数组的最大值为:", max_val)
print("数组的最小值为:", min_val)
print("数组的差值为:", diff)
```
输出结果为:
```
数组的最大值为: 8
数组的最小值为: 1
数组的差值为: 7
```
阅读全文