1、使用可变参数,实现函数,求函数参数的平均值。
#include <stdio.h>
#include<stdarg.h>
int average(int n,...){
va_list arg;
int i = 0;
int sum = 0;
va_start(arg,n);
for(i = 0;i < n;i++){
sum += va_arg(arg,int);
}
return sum/n;
va_end(arg);
}
int main(){
int a = 1;
int b = 2;
int c = 3;
int avg1 = average(2,a,c);
int avg2 = average(3,a,b,c);
printf("avg1 = %d,avg2 = %d\n",avg1,avg2);
return 0;
}
2、使用可变参数,实现函数,求函数参数的最大值。
#include <stdio.h>
#include<stdarg.h>
int Max(int n,...){
va_list(arg);
int i = 0;
int max_value = 0;
va_start(arg,n);
for(i = 0;i < n;i++){
int tmp = va_arg(arg,int);
if(tmp > max_value)
max_value = tmp;
}
return max_value;
va_end(arg);
}
int main(){
int max1 = Max(5,4,9,8);
int max2 = Max(7,13,21,4,2);
printf("max1 = %d,max2 = %d\n",max1,max2);
return 0;
}