我现在正在学习C,并尝试使用可变数量的参数编写自己的函数,我想使用它。这可能吗? 我找到了如何创建这样一个函数的示例,但我不知道如何使用它们。 这是我所拥有的:
double ftest(int amount, double dA1,...)
{
double dsumm = 0.0;
for (int i=1;i <= amount; i++){
dsum=1/dA1+1/dA2 //?? here is my Question how can I add all the parameters the user entered?
}
return dRges;
}
好吧,在我的原始帖子中,它被认为是重复的,但我想做的不仅仅是赚一笔钱。我想用它做不同的计算。就像我希望能够将它们全部作为 dA1 到 dAn = 参数数量的它们一样。然后我想做计算。
试试这个(内联评论):
#include <stdio.h>
#include <stdarg.h> //This includes all the definitions for variable argument lists.
double add_nums(int amount, ...)
{
double total = 0.0;
va_list args; //This is working space for the unpacking process. Don't access it directly.
va_start(args, amount); //This says you're going to start unpacking the arguments following amount.
for (int i = 0; i < amount ; ++i) {
double curr=va_arg(args, double);//This extracts the next argument as a double.
total += curr;
}
va_end(args); //This says you've finished and any behind the scenes clean-up can take place.
//Miss that line out and you might get bizarre behaviour and program crashes.
return total;
}
int main()
{
double total=add_nums(4, 25.7, 25.7, 50.0, 50.0);
printf("total==%fn",total);
return 0;
}
预期产出:
total==151.400000
这里有一个陷阱,因为它是无效的:
double total=add_nums(4, 25.7, 25.7, 50, 50.0);
第四个参数(50
)是一个整数。您必须确保在文字中输入小数,以确保它们是真正的double
。
是的,这是可能的,也是直接的:
#include <stdarg.h>
double ftest(int number, double dA1, ...)
{
va_list args;
va_start(args, dA1);
double sum = dA1;
for (int i = 1; i < number; i++)
sum += va_arg(args, double);
va_end(args);
return sum;
}
并在某处的函数中使用:
double d1 = ftest(2, 1.1, 2.3);
double d2 = ftest(1, 34.56);
double d3 = ftest(5, 21.23, 31.45, 9876.12, -12.3456, -199.21);