I want to sum X complex numbers, but this code returns me:
-9.3e+61 + -1.9e+062i
typedef struct complex{
double real;
double imag;
} complex;
complex sum(int length, ...)
{
va_list param;
va_start(param, length);
complex out = {0, 0};
for(int i = 0;i<length;i++)
{
out.real += va_arg(param, complex).real;
out.imag += va_arg(param, complex).imag;
}
va_end(param);
return out;
}
when i quote real / imag part in for, it returns right real / imag result.
main:
int main()
{
complex result;
complex a = {3.1,-2.3};
complex b = {0.5,-3};
complex c = {0,1.2};
result = sum(3,a,b,c);
printf("Sum is %.2g + %.2gi. \n", result.real, result.imag);
return 0;
}
What should i change to make it works?
The problem is that every time you call va_arg
, it will take out one whole complex
struct. Since you call it twice per loop, you take out 2 different complex
struct, which is incorrect.
You need to cache the result and access the members later:
for (int i = 0; i < length; i++)
{
complex currArg = va_arg(param, complex);
out.real += currArg.real;
out.imag += currArg.imag;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.