c语言写一函数实现求4个整数中最大的数及平均值,主函数输入数据,并调用函数完成该功能。
时间: 2024-02-18 09:04:26 浏览: 30
好的,以下是实现您要求的函数和主函数的代码:
```c
#include <stdio.h>
void max_avg(int a, int b, int c, int d, int *max, float *avg) {
*max = a;
if (*max < b) *max = b;
if (*max < c) *max = c;
if (*max < d) *max = d;
*avg = (a + b + c + d) / 4.0;
}
int main() {
int a, b, c, d, max;
float avg;
printf("请输入4个整数:\n");
scanf("%d%d%d%d", &a, &b, &c, &d);
max_avg(a, b, c, d, &max, &avg);
printf("最大值为:%d\n平均值为:%.2f\n", max, avg);
return 0;
}
```
这里定义了一个 `max_avg` 函数,它接受四个整数和两个指针作为参数,其中指针 `max` 用于存储最大值,指针 `avg` 用于存储平均值。函数内部通过比较大小找到最大值,并计算平均值。
在主函数中,首先从用户输入中获取四个整数,然后调用 `max_avg` 函数,将结果存储在变量 `max` 和 `avg` 中,最后输出结果。
相关问题
c语言写一个函数求出n个整数的和值,主函数通过键盘输入10个整数,然后通过函数调用求1
好的,以下是使用C语言编写的代码,实现了你的需求:
```c
#include <stdio.h>
int sum_array(int arr[], int n) {
/*
求一个数组的和
参数:
arr:数组
n:数组长度
返回值:
数组的和
*/
int sum = 0;
for (int i = 0; i < n; i++) {
sum += arr[i];
}
return sum;
}
int main() {
/*
主函数,通过键盘输入10个整数,求和并输出平均值
*/
int n = 10;
int arr[n];
for (int i = 0; i < n; i++) {
printf("请输入第%d个整数:", i+1);
scanf("%d", &arr[i]);
}
// 求和
int total = sum_array(arr, n);
// 求平均值
int avg = total / n;
printf("这%d个整数的和为:%d\n", n, total);
printf("这%d个整数的平均值为:%d\n", n, avg);
return 0;
}
```
你可以将以上代码保存为一个文件并编译运行,就可以看到输出结果了。
用C语言写一个函数求出n个整数的和值,主函数通过键盘输入10个整数,然后通过函数调用求1
好的,以下是使用C语言编写的代码,实现了你的需求:
```c
#include <stdio.h>
int sum_array(int arr[], int n) {
/*
求一个数组的和
参数:
arr:数组
n:数组长度
返回值:
数组的和
*/
int sum = 0;
for (int i = 0; i < n; i++) {
sum += arr[i];
}
return sum;
}
int main() {
/*
主函数,通过键盘输入10个整数,求和并输出平均值
*/
int n = 10;
int arr[n];
for (int i = 0; i < n; i++) {
printf("请输入第%d个整数:", i+1);
scanf("%d", &arr[i]);
}
// 求和
int total = sum_array(arr, n);
// 求平均值
int avg = total / n;
printf("这%d个整数的和为:%d\n", n, total);
printf("这%d个整数的平均值为:%d\n", n, avg);
return 0;
}
```
你可以将以上代码保存为一个文件并编译运行,就可以看到输出结果了。
相关推荐
![c](https://img-home.csdnimg.cn/images/20210720083646.png)
![c](https://img-home.csdnimg.cn/images/20210720083646.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)
![](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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)