1..使用可变参数,实现函数,求函数参数的平均值。
2.使用可变参数,实现函数,求函数参数的最大值。
3.模拟实现printf函数,可完成下面的功能
//
//能完成下面函数的调用。
//print("s ccc d.\n","hello",'b','i','t',100);
//函数原型:
//print(char *format, ...)
//
1. 使用可变参数,实现函数,求函数参数的平均值。
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<stdlib.h>
#include<stdarg.h>
int average(int n, ...)
{
va_list arg;
va_start(arg, n);
int i = 0;
int sum = 0;
while (i < n)
{
int data = va_arg(arg, int);
sum = sum + data;
i++;
}
va_end(arg);
return sum / n;
}
int main()
{
int aver = 0;
aver = average(5, 1, 20, 40,50,70);
printf("%d", aver);
}
2. 使用可变参数,实现函数,求函数参数的最大值。
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<stdlib.h>
#include<stdarg.h>
int max_h(int n, ...)
{
va_list arg;
va_start(arg, n);
int i = 0;
int max = 0;
int num = 0;
while (i < n)
{
num = va_arg(arg, int);
if (num>max)
max = num;
i++;
}
va_end(arg);
return max;
}
int main()
{
int max = 0;
max = max_h(5,1,2,3,4,5);
printf("最大值为%d", max);
}
3.模拟实现printf函数,可完成下面的功能
//
//能完成下面函数的调用。
//print("s ccc d.\n","hello",'b','i','t',100);
//函数原型:
//print(char *format, ...)
//
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<stdlib.h>
#include<stdarg.h>
void printf_a(char *s, ...)
{
va_list arg;
char c = NULL;
va_start(arg, s);
while (*s != '\0')
{
if (*s == 'c')
{
putchar(va_arg(arg, char));
}
else
if (*s == 'd')
{
printf("%d", va_arg(arg, int));
}
else
if (*s == 's')
{
puts(va_arg(arg, char *));
}
s++;
}
va_end(arg);
}
int main()
{
printf_a("s ccc d \n", "hello", 'b', 'i', 't', 100);
system("pause");
}