C语言中可变参数的应用

可变参数要配合va_list、va_start、va_arg、va_end这些宏来使用,而这些宏都在strarg.h中定义,所以在运用这些宏时,要加上这个头文件。

可变参数就是只有一个参数是固定的,其他参数都是可变的。

下面我举一些可变参数的例子,希望大家能理解。

求输的平均数。

程序代码:

#include <stdio.h>

#include <stdarg.h>


int average(int val, ...)

{

       va_list arg;

        int sum = 0;

        int i = 0;

       va_start(arg, val);

        //va_arg();

       

        for (i = 0; i < val; i++)

       {

              sum += va_arg(arg, int);

       }

       va_end(arg);

        return sum / val;

}

int main()

{

        int ret1,ret2,ret3,ret4;

       ret1 = average(3, 1, 2, 3);

       printf( "ret1 = %d\n", ret1);

        ret2 = average(5, 1, 2, 3,4,5);

       printf( "ret2 = %d\n", ret2);

       

        ret3 = average(6, 1, 2, 3,6,7,8);

       printf( "ret3 = %d\n", ret3);

       

        ret4 = average(10, 1, 2, 3,4,5,6,7,8,9,10);

       printf( "ret4 = %d\n", ret4);

       system( "pause");

        return 0;

}

模拟实现printf,要求功能:print("ccc\ts!",'b','i','t',"welcome to you")

程序代码:

#include<stdio.h>

#include<stdarg.h>

void my_printf(char *string, ...)

{

        va_list arg;

        va_start(arg, string );

        while (*string )

       {

               switch (*string )

              {

               case 'c' :

              {

                                   char ch = va_arg (arg, char);

                                  putchar(ch);

                                   break;

              }

               case 's' :

              {

                                   char *p = va_arg (arg, char*);

                                   while (*p)

                                  {

                                         putchar(*p);

                                         p++;

                                  }

                                   break;

              }

               default:

              {

                              putchar(* string);

                              break;

              }

              }

               string++;

       }

        va_end(arg);

}

int main()

{

       my_printf( "ccc\ts!", 'b' , 'i', 't', "welcome to you" );

       system( "pause");

        return 0;

}

希望这些例子可以帮助你们更好的理解可变参数。

你可能感兴趣的:(程序,include,平均数,average)