我写了以下代码:
#include <stdarg.h>
#include <stdio.h>
double average(int count, ...)
{
va_list ap;
int j;
double sum = 0;
va_start(ap, count); /* Requires the last fixed parameter (to get the address) */
for (j = 0; j < count; j++) {
sum += va_arg(ap, double); /* Increments ap to the next argument. */
}
va_end(ap);
return sum / count;
}
int main(){
int count = 3;
double result = average(count, 10, 20, 20);
printf("result = %f\n", result);
}
Run Code Online (Sandbox Code Playgroud)
我的目的是计算参数总和的平均值(第一个参数除外,它是参数的数量).但打印值为0.00000.代码有什么问题?
您正在尝试读取int的double,将无法正常工作.cast并获得arg作为int:
sum += (double) va_arg (ap, int); /* Increments ap to the next argument. */
Run Code Online (Sandbox Code Playgroud)
输出:
result = 16.666667
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
42 次 |
| 最近记录: |