【发布时间】:2021-07-08 03:53:40
【问题描述】:
我想通过满足条件来传递不同数量的参数给函数。但问题是参数必须是函数的相同数量的参数。在每个条件下,我都有不同的变量值,我想将它们作为参数传递。如何避免这种情况并成功执行我的代码。
#include<stdio.h>
float file_w(float root1,float root2, float real,float imag)
{
FILE *fileWrite;
fileWrite= fopen("fileNames.txt", "a+");
if(root2==NULL && real==NULL && imag==NULL){
fprintf(fileWrite,"%.2f",root1);
fclose(fileWrite);
}
}
float file_r()
{
system("cls");
printf("\n\n\n\t\t\t\tCalculation History\n\n\t\t\t\t");
FILE *file;
char c;
file=fopen("fileName.txt","r");
if(file==NULL)
{
printf("file not found");
}
else
{
while(!feof(file))
{
c=fgetc(file);
printf("%c",c);
}
fclose(file);
printf("\n");
system("Pause");
main();
}
}
int main(){
double a, b, c, discriminant, root1, root2, realPart, imagPart;
int opt;
printf("Enter coefficients a, b and c: \n");
scanf("%lf", &a);
scanf("%lf",&b);
scanf("%lf",&c);
discriminant = b * b - 4 * a * c;
if (discriminant > 0)
{
root1 = (-b + sqrt(discriminant)) / (2 * a);
root2 = (-b - sqrt(discriminant)) / (2 * a);
printf("\n\t\t\t\troot1 = %.2lf and root2 = %.2lf\n\n\t\t\t\t", root1, root2);
file_w(root1,root2);
}
else if (discriminant == 0)
{
root1 = root2 = -b / (2 * a);
printf("\n\t\t\t\troot1 = root2 = %.2lf\n\n\t\t\t\t", root1);
file_w(root1);
}
else
{
realPart = -b / (2 * a);
imagPart = sqrt(-discriminant) / (2 * a);
printf("\n\t\t\t\troot1 = %.2lf + %.2lfi and root2 = %.2f - %.2fi\n\n\t\t\t\t", realPart, imagPart, realPart, imagPart);
file_w(realPart,imagPart);
}
return 0;
}
【问题讨论】:
-
我删除了c++11 标签,因为您的问题似乎是关于 C 的,而 C++ 是完全不同的语言。
-
要传递不同数量的参数,请使用
float file_w(float root1,...)并调用file_w(1.0)、file_w(1.0, 2.0)或file_w(1.0, 2.0,3.0, 4.0).. 剩下的就是你想如何传达参数的数量。 -
这不是解决您问题的好方法。可以有函数接受可变数量的参数,但函数不会被告知实际传递了多少参数。因此,如果第一个参数是
3,您无法知道它是3还是3+4i,如果您猜错了,您将导致未定义的行为(可能使用垃圾值)。 -
通常的做法是避免在 C 中使用 variadic functions,因为它们不是类型安全的。如果您绝对需要它们,请考虑使用
va_start、va_arg、va_end,如stdarg(3) 中所述 -
while(!feof(file))--> Why is “while ( !feof (file) )” always wrong?