【问题标题】:sum complex numbers in function with a variable number of parameters对具有可变数量参数的函数中的复数求和
【发布时间】:2013-02-27 09:38:33
【问题描述】:

我想对 X 个复数求和,但这段代码返回了我:

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

当我在 for 中引用 real / imag 部分时,它会返回正确的 real / imag 结果。

主要:

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

我应该改变什么才能让它工作?

【问题讨论】:

  • 你知道C已经有complex numbers
  • 我知道,但我想自己定义。
  • 问题是每次调用va_arg,都会取出一个完整的complex struct。由于您每次循环调用它两次,因此您取出了 2 个不同的 complex 结构,这是不正确的。您需要缓存结果并稍后访问成员。
  • @nhahtdh 为什么不将其添加为可以接受的答案?
  • 顺便说一句,你可以使用printf("Sum is %.2g %+.2gi")输出3-2i或1.3+4.1i

标签: c function sum complex-numbers


【解决方案1】:

问题是每次调用va_arg,都会取出一个完整的complex struct。由于您每次循环调用它两次,因此您取出了 2 个不同的 complex 结构,这是不正确的。

您需要缓存结果并稍后访问成员:

for (int i = 0; i < length; i++)
{
    complex currArg = va_arg(param, complex);
    out.real += currArg.real;
    out.imag += currArg.imag;
}

【讨论】:

    猜你喜欢
    • 2023-03-12
    • 2011-12-24
    • 1970-01-01
    • 1970-01-01
    • 2021-10-07
    • 1970-01-01
    • 1970-01-01
    • 2013-03-14
    • 2023-03-25
    相关资源
    最近更新 更多