Variable Parameter Function

given this function

double avg(double v1,double v2,...)
{
    double sum=v1+v2;
    int counter=2;
    double temp;
    va_list pargs;
    va_start(pargs,v2);
    while((temp=va_arg(pargs,double))!=0.0)
    {
        sum+=temp;
        counter++;
    }
    va_end(pargs);
    return sum/counter;
}

This call printf("%lf\n",avg(3.0,4.5,4.5,3.0,0.0))returns the correct result, but if I delete the last parameter 0.0, it prints -321738127312000000000.0000000, but the sum and counter have the correct values. I don’t seem to understand why I need to check that !=0.0and have the last parameter0.0

+3
source share
5 answers

- , . : , , (, printf scanf), , 0, .

, , , , , , , .

+6

!= 0.0, , .

:

  • , , avg (3, 4.3, 2.0, 3.0);
  • , avg (4.3, 2.0, 3.0, 0.0);

, :

#define avg(v1, v2, ...) _avg((v1), (v2), __VA_ARGS__, 0.0)

double _avg(double v1,double v2,...) 
{ 
    /* same code, just prefixing function name with _ */

:

avg(3.0, 3.0, 0.0, 100.0, 100.0) 

3.0, va_list. "" ...

+3

, . , , . .

, != 0.0, (0), . - , for args.

+1

(0.0) , , . ( ) , , - . va_arg, , , , , , (v2), (double). , .

+1

, , , . , , avg(). , ( dfa).

, , , . , , . , avg() float.

0

Source: https://habr.com/ru/post/1708212/


All Articles