c语言 函数可变参数列表
1、编写函数求一系列值的平均数,参数数目不确定:
#include <stdarg.h> double average(int n_values, ...) { va_list var_arg; int count; double sum=0; va_start(var_arg, n_values); for(count=0; count<n_values; count++) { sum+=va_arg(var_arg, double); } va_end(var_arg); return sum/n_values; } int main() { printf("average1=%f\n",average(5, 1.1, 2.2, 3.3, 4.4, 5.5)); printf("average2=%f\n",average(2, 88.0, 66.6)); return 0; }
输出结果为:
average1=3.300000 average2=77.300000