C++ 关于类数组返回函数的二次代数建议
我有个问题。我想写一个方法,它使用PQ公式来计算二次代数上的零C++ 关于类数组返回函数的二次代数建议,c++,math,algebra,C++,Math,Algebra,我有个问题。我想写一个方法,它使用PQ公式来计算二次代数上的零 正如我所见C++不支持数组,不像我通常使用的C。 如何返回零、1或2个结果? 如果没有数组,还有其他方法吗 实际上我不喜欢指针,所以我的实际代码被破坏了 如果有人能帮助我,我会很高兴的 float*calculateZeros(浮点p,浮点q) { 浮点数*x1,*x2; 如果((p)/2)*((p)/2)-(q)
正如我所见C++不支持数组,不像我通常使用的C。 如何返回零、1或2个结果? 如果没有数组,还有其他方法吗
实际上我不喜欢指针,所以我的实际代码被破坏了 如果有人能帮助我,我会很高兴的float*calculateZeros(浮点p,浮点q)
{
浮点数*x1,*x2;
如果((p)/2)*((p)/2)-(q)<0)
抛出std::异常(“无零!”);
x1*=-((p)/2)+sqrt(静态(p)/2)*((p)/2)-(q));
x2*=-((p)/2)-sqrt(静态(p)/2)*((p)/2)-(q));
浮动返回值[1];
返回值[0]=x1;
返回值[1]=x2;
返回x1!=x2?返回值[0]:x1;
}
实际上,这段代码是不可编译的,但这是我到目前为止所做的代码。这段代码有很多问题;首先,我将删除所有那些完全不必要的括号,它们只会使代码(更)难以阅读:
float* calculateZeros(float p, float q)
{
float *x1, *x2; // pointers are never initialized!!!
if ((p / 2)*(p / 2) - q < 0)
throw std::exception("No Zeros!"); // zeros? q just needs to be large enough!
x1 *= -(p / 2) + sqrt(static_cast<double>((p / 2)*(p / 2) - q);
x2 *= -(p / 2) - sqrt(static_cast<double>((p / 2)*(p / 2) - q);
// ^ this would multiply the pointer values! but these are not initialized -> UB!!!
float returnValue[1];
returnValue[0] = x1; // you are assigning pointer to value here
returnValue[1] = x2;
return x1 != x2 ? returnValue[0] : x1;
// ^ value! ^ pointer!
// apart from, if you returned a pointer to returnValue array, then you would
// return a pointer to data with scope local to the function – i. e. the array
// is destroyed upon leaving the function, thus the pointer returned will get
// INVALID as soon as the function is exited; using it would again result in UB!
}
现在还有最后一个问题:由于double的精度有限,可能会出现舍入错误(如果使用float,这个问题甚至值得一提;我建议将所有float设置为double、参数和返回值!)。你不应该为了精确的相等而比较(<代码> SoValue=0),但是考虑一些ε来覆盖非常舍入的值:
-epsilon < someValue && someValue < +epsilon
-epsilon
好的,在给定的情况下,涉及到两个最初精确的比较,我们可能希望尽可能少地进行ε比较。因此:
double d = r - s;
if(d > -epsilon)
{
// considered 0 or greater than
h = -h;
if(d < +epsilon)
{
// considered 0 (and then no need to calculate the root at all...)
results.push_back(h);
}
else
{
// considered greater 0
double r = sqrt(d);
results.push_back(h - r);
results.push_back(h + r);
}
}
double d=r-s;
if(d>-epsilon)
{
//被认为是0或大于
h=-h;
if(d<+ε)
{
//考虑0(然后根本不需要计算根…)
结果:推回(h);
}
其他的
{
//认为大于0
双r=sqrt(d);
结果:推回(h-r);
结果:推回(h+r);
}
}
ε值?好吧,要么使用一个足够小的固定值,要么根据两个值中的较小值(乘以一些小因子)动态计算它——并且确保它为正。。。你可能对这件事感兴趣。你不必关心C++,这个问题对于使用IEEE74表示的所有语言都是一样的。“我看到C++不支持数组……”“我看到C++不支持数组”——BoLink。静态数组有
std::array
,动态数组有std::vector
。还有旧的C样式数组(但请不要使用它们)。我可以建议在负增量的情况下不要抛出异常吗?零实解是可能的预期结果之一。float*x1,*x2代码>--为什么是这些指针?我猜这是当你尝试从你喜欢的语言翻译成C++,逐行学习,而不学习C++。你完全错了C++语言的基础。啊,我不知道C++有数组。我来看看。谢谢,如果我做完了,我会回来的。
double d = r - s;
if(d > -epsilon)
{
// considered 0 or greater than
h = -h;
if(d < +epsilon)
{
// considered 0 (and then no need to calculate the root at all...)
results.push_back(h);
}
else
{
// considered greater 0
double r = sqrt(d);
results.push_back(h - r);
results.push_back(h + r);
}
}