吾爱程序员:这里有好玩的游戏和软件
当前位置:首页C语言教程 → 如何计算 C 中可变数量的参数

如何计算 C 中可变数量的参数

来源:网络 | 更新时间:2022-01-14 20:27:50
C 支持可变数量的参数。但是没有语言提供方法来找出传递的参数总数。用户必须通过以下方式之一处理此问题: 1) 通过将第一个参数作为参数计数传递。 2) 通过将最后一个参数作为 NULL(或 0)传递。 3)使用一些类似 printf(或 scanf)的机制,其中第一个参数有其余参数的占位符。 以下是使用第一个参数arg_count保存其他参数计数的示例。

#include <stdarg.h>
#include <stdio.h>

// this function returns minimum of integer numbers passed. First 
// argument is count of numbers.
int min(int arg_count, ...)
{
int i;
int min, a;

// va_list is a type to hold information about variable arguments
va_list ap; 

// va_start must be called before accessing variable argument list
va_start(ap, arg_count); 

// Now arguments can be accessed one by one using va_arg macro
// Initialize min as first argument in list 
min = va_arg(ap, int);

// traverse rest of the arguments to find out minimum
for(i = 2; i <= arg_count; i++) {
if((a = va_arg(ap, int)) < min)
min = a;
} 

//va_end should be executed before the function returns whenever
// va_start has been previously used in that function 
va_end(ap); 

return min;
}

int main()
{
int count = 5;

// Find minimum of 5 numbers: (12, 67, 6, 7, 100)
printf("Minimum value is %d", min(count, 12, 67, 6, 7, 100));
getchar();
return 0;
}
输出: Minimum value is 6  

最新文章

热点资讯

手游排行榜

CopyRight 2020-2030吾爱程序员

鄂ICP备2021004581号-8

本站资源收集于网络,如有侵权请联系我们:35492删除0109@qq.com