1. 程式人生 > >使用可變引數,實現函式,求函式引數的平均值。

使用可變引數,實現函式,求函式引數的平均值。

#include<stdio.h>
#include<stdarg.h>
double average(int n, ...)
{
    va_list arg;
    int i = 0;
    double sum = 0;
    va_start(arg, n);
    for(i = 0; i < n; i++)
    {
        sum = sum + va_arg(arg, double);
    }
    va_end(arg);
    return sum / n;
}
int main()
{
    double a = 1.3
; double b = 2.5; double c = 3.7; double avg1 = average(2, a, b); double avg2 = average(3, a, b, c); printf("avg1 = %lf\n", avg1); printf("avg2 = %lf\n", avg2); system("pause"); return 0; }