用c语言定义一个指针函数求任意n的平均值
时间: 2024-04-29 22:21:17 浏览: 9
```c
#include <stdio.h>
double* average(int arr[], int n) {
static double result[2]; // 定义一个静态数组,存储平均值和元素个数
int sum = 0;
for (int i = 0; i < n; i++) {
sum += arr[i];
}
result[0] = (double)sum / n; // 计算平均值
result[1] = n; // 存储元素个数
return result; // 返回指向result数组的指针
}
int main() {
int arr[] = { 1,2,3,4,5 };
int n = sizeof(arr) / sizeof(arr[0]);
double* p = average(arr, n);
printf("平均值为%.2lf,元素个数为%d\n", *p, (int)*(p + 1));
return 0;
}
```
相关问题
用c语言定义一个指针函数求字符串ch的个数
```
#include <stdio.h>
int count_chars(char *ch) {
int count = 0;
while (*ch != '\0') {
count++;
ch++;
}
return count;
}
int main() {
char str[] = "hello world";
int count = count_chars(str);
printf("The number of characters in the string is %d\n", count);
return 0;
}
```
该程序定义了一个指针函数 `count_chars`,它接收一个指向字符数组的指针 `char *ch`,并返回该字符串的字符数。在函数中,使用一个 `while` 循环遍历字符串,每遇到一个字符就将计数器加一,直到遍历完整个字符串。最后返回计数器的值。在 `main` 函数中,我们定义了一个字符串 `str`,调用 `count_chars` 函数并打印结果。
用c语言,定义一个函数求三个数的最大值
可以使用以下代码定义一个函数,这个函数可以求出三个数中的最大值:
```c
int max(int a, int b, int c) {
int max = a;
if (b > max) {
max = b;
}
if (c > max) {
max = c;
}
return max;
}
```
这个函数接受三个参数,分别为a、b、c三个整数,然后通过比较它们的大小,得出最大值并返回。