我现在正在学习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 =参数的数量。然后我想做计算。
答案 0 :(得分:3)
试试这个(评论内联):
#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==%f\n",total);
return 0;
}
预期产出:
total==151.400000
这里有一个陷阱,因为这是无效的:
double total=add_nums(4, 25.7, 25.7, 50, 50.0);
第四个参数(50
)是一个整数。你必须确保在文字中加上小数,以确保它们是真正的double
。
答案 1 :(得分:2)
是的,这是可能的,直截了当的:
#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);