用C语言写“给定n个数,求这n个数序列的和,最大值,最小值”
时间: 2024-10-17 10:03:46 浏览: 56
在C语言中,你可以通过以下步骤计算给定数组的和、最大值和最小值:
```c
#include <stdio.h>
// 函数声明
void find_sum_max_min(int arr[], int n);
int get_sum(int arr[], int n);
int get_max(int arr[], int n);
int get_min(int arr[], int n);
int main() {
int n, *arr;
// 输入数组长度和元素
printf("Enter the number of elements (n): ");
scanf("%d", &n);
arr = (int*)malloc(n * sizeof(int));
printf("Enter the numbers: ");
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
// 调用函数并打印结果
printf("Sum: %d\n", get_sum(arr, n));
printf("Max value: %d\n", get_max(arr, n));
printf("Min value: %d\n", get_min(arr, n));
// 清理内存
free(arr);
return 0;
}
// 计算数组总和
int get_sum(int arr[], int n) {
int sum = 0;
for (int i = 0; i < n; i++) {
sum += arr[i];
}
return sum;
}
// 获取数组最大值
int get_max(int arr[], int n) {
int max = arr[0];
for (int i = 1; i < n; i++) {
if (arr[i] > max) {
max = arr[i];
}
}
return max;
}
// 获取数组最小值
int get_min(int arr[], int n) {
int min = arr[0];
for (int i = 1; i < n; i++) {
if (arr[i] < min) {
min = arr[i];
}
}
return min;
}
```
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![text/plain](https://img-home.csdnimg.cn/images/20250102104920.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)