一维数组:求一批数中最大值与最小值的差
时间: 2023-04-24 11:01:32 浏览: 273
可以先遍历一遍数组,找到最大值和最小值,然后用最大值减去最小值即可得到差值。具体实现可以参考以下代码:
int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
int len = sizeof(arr) / sizeof(int);
int max = arr[], min = arr[];
for (int i = 1; i < len; i++) {
if (arr[i] > max) {
max = arr[i];
}
if (arr[i] < min) {
min = arr[i];
}
}
int diff = max - min;
printf("最大值与最小值的差为:%d\n", diff);
相关问题
求一批数中最大值与最小值的差编写一个程序
编写一个程序来找到一组数值中的最大值和最小值,并计算它们之间的差,可以使用多种编程语言。这里是一个使用Python的例子:
```python
def find_difference(numbers):
# 确保输入的是列表或可迭代对象
if not isinstance(numbers, (list, tuple)):
numbers = list(numbers)
# 初始化最大值和最小值为列表的第一个元素
max_value = min_value = numbers[0] if numbers else None
# 遍历列表,更新最大值和最小值
for num in numbers:
if num > max_value:
max_value = num
elif num < min_value:
min_value = num
# 计算差值
difference = max_value - min_value if max_value and min_value else None
return difference
# 示例
numbers_list = [5, 3, 9, 1, 7]
result = find_difference(numbers_list)
print(f"数组 {numbers_list} 中的最大值与最小值之差是: {result}")
求一批数中最大值,最小值的差和积程序编程
以下是 Python 代码实现:
```python
nums = [3, 7, 9, 2, 8, 6] # 示例数字列表
# 求最大值
max_num = max(nums)
print("最大值为:", max_num)
# 求最小值
min_num = min(nums)
print("最小值为:", min_num)
# 求差值
diff = max_num - min_num
print("差值为:", diff)
# 求积
product = 1
for num in nums:
product *= num
print("积为:", product)
```
输出结果:
```
最大值为: 9
最小值为: 2
差值为: 7
积为: 18144
```
阅读全文