进行函数可变参数的实现。
va_list
:
适用于 va_start()、va_arg() 和 va_end() 这三个宏存储信息的类型。void va_start(va_list ap, last_arg)
:
初始化 ap,其中 last_arg 是最后一个传递给函数的已知固定参数。type va_arg(va_list ap, type)
:
返回列表中类型为 type 的下一个参数。void va_end(va_list ap)
:
在函数返回前需进行调用。
实例程序:求解 average(a,b)-average(c,d,e).
# include <cstdio>
# include <cctype>
# define print(x,y) write(x), putchar(y)template <class T>
inline T read(const T sample) {T x=0; bool f=0; char s;while(!isdigit(s=getchar())) f|=(s=='-');for(; isdigit(s); s=getchar()) x=(x<<1)+(x<<3)+(s^48);return f? -x: x;
}
template <class T>
inline void write(T x) {static int writ[50], w_tp=0;if(x<0) putchar('-'), x=-x;do writ[++w_tp]=x-x/10*10, x/=10; while(x);while(putchar(writ[w_tp--]^48), w_tp);
}# include <cstdarg>double avg(int num_args, ...) {double ans = 0; va_list s;va_start(s, num_args);for(int i=0; i<num_args; ++i)ans += va_arg(s, double);va_end(s); return ans/num_args;
}int main() {double a, b, c, d, e;scanf("%lf%lf%lf%lf%lf",&a,&b,&c,&d,&e);printf("%.4lf\n", avg(2,a,b)-avg(3,c,d,e));return 0;
}