简体   繁体   English

用可变数量的参数求和函数中的复数

[英]sum complex numbers in function with a variable number of parameters

I want to sum X complex numbers, but this code returns me: 我想对X个复数求和,但是这段代码返回了我:

-9.3e+61 + -1.9e+062i -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. 当我引用real / imag part时,它将返回正确的real / imag结果。

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. 问题在于,每次调用va_arg ,它将取出一个完整的complex结构。 Since you call it twice per loop, you take out 2 different complex struct, which is incorrect. 由于每个循环调用两次,因此取出2个不同的complex结构,这是不正确的。

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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM