gpt4 book ai didi

C++ 复项多项式函数评估失败

转载 作者:行者123 更新时间:2023-11-28 02:04:53 27 4
gpt4 key购买 nike

我正在尝试实现一个简单的 Durand-Kerner求根算法,但在尝试编译代码时出现错误。这是我目前所拥有的:

#include <iostream>
#include <string> // std::stod
#include <complex>

typedef std::complex<double> cplx;

// f(x)
/************************************************/
/// This function doesn't want to be compiled, but
/// it's implemented the same way as the one below
/*************************************************/
cplx f(cplx &coeff, cplx &term, int length)
{
cplx sum {0., 0.};
for (int k=0; k<length; ++k)
{
sum += coeff[k] * pow(term[k], length - 1 - k);
}
return sum;
}

int main(int argc, char *argv[])
{
cplx *terms {new cplx[argc-1]};
cplx *initial {new cplx[argc-1]};

// Convert command-line chars to numbers
for (int k=1; k<argc; ++k)
terms[k-1] = std::stod(argv[k]);

// Initialize the seed roots
for (int k=0; k<argc-1; ++k)
initial[k] = pow(cplx(0.4, 0.9), k);

/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

/*********************************************************/
/// This one is the same as f(x) above, but this one works
/*********************************************************/
cplx s {0., 0.};
for (int k=0; k<argc-1; ++k)
s += terms[k] * pow(initial[k], argc - 2 - k);
std::cout << s << "\n";

return 0;
}

在尝试执行多项式 f(x)(第一个函数)的计算时,我不断收到此错误:“~/Documents/cpp/Durand-Kerner/main.cpp|13|错误:不匹配对于“operator[]”(操作数类型为“cplx {aka std::complex}”和“int”)|”。

虽然错误很明显,但我不明白为什么,因为在注释“~~~”行下方实现的函数 f(x) 有效。如果我注释掉 f(x) 函数,我可以编译,但不能编译函数?

我看不出两者之间没有什么不同,也许除了“length”与显式“argc”,但“length”将作为“argc-1”传递给函数,所以我真的不明白为什么错误? (我目前正在学习 C++,如果这里很重要的话)

最佳答案

问题出现在这里:

sum += coeff[k] * pow(term[k], length - 1 - k);

但实际问题可能出在您发送引用(cplx &coeff、cplx &term)的函数的 header 中,但您希望将它们用作数组或指针。解决方法可能是这样的:

//f(x)

cplx f(cplx *coeff, cplx *term, int length)
{
cplx sum {0., 0.};
for (int k=0; k<length; ++k)
{
sum += coeff[k] * pow(term[k], length - 1 - k);
}
return sum;
}

如您所见,我已将 & 符号更改为 *。

关于C++ 复项多项式函数评估失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37911882/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com