我有以下C代码。计算 simple_root 的语句出现两次。我想知道是否有更好的方法来组织代码,使该语句仅出现一次。
如果将 simple_root 放在最后一个 之后,则可能会出现错误,例如前两个条件不匹配。如果我错了,请纠正我。
if(fabs(quartic_polynomial(a, b, c, d, e, secDerivRoot_1)) < 1e-6)
{
triple_root = secDerivRoot_1;
simple_root = -b/a - 3*triple_root;
}
else if (fabs(quartic_polynomial(a, b, c, d, e, secDerivRoot_2)) < 1e-6)
{
triple_root = secDerivRoot_2;
simple_root = -b/a - 3*triple_root;
}
else
printf("Something is wrong. No common root with its 2nd derivative. \n");
答案 0 :(得分:0)
您在评论中缺少了一些内容
如果将simple_root放在最后一个之后,则存在出错的风险,例如前两个条件不匹配
已经是这种情况-如果您不匹配这两个,则triple_root
和simple_root
尚未设置。我不确定在这段代码后如何使用它们,或者您的错误处理方式是什么。您可以在printf
语句后立即返回,也可以将triple_root
设置为NaN
。
然后,您可以将simple_root公式移至if
语句下方。或者,您可以将其放入函数中。单行功能可以使代码更易于理解。
答案 1 :(得分:0)
我认为以下应该这样做。我尚未对其进行编译或测试,因此您可能需要进行一些调整。
但是您的原始措辞更具可读性,我真的发现以这种方式进行这样做没有任何优势。
使用这种方法,您总是会同时执行两个quartic_polynomial()
调用,而不是有时仅执行一个调用,这可能会严重影响CPU的使用和时间,而不是复制一行代码。
我很好奇两个if
语句是否都可以成立。在这种情况下您该怎么办?还是可以选择自己喜欢的人?
{
int sec_1 = (fabs(quartic_polynomial(a, b, c, d, e, secDerivRoot_1) < 1e-6);
int sec_2 = (fabs(quartic_polynomial(a, b, c, d, e, secDerivRoot_2) < 1e-6);
if (! (sec_1 || sec_2)) {
printf("Something is wrong. No common root with its 2nd derivative. \n");
} else {
if (sec_1)
triple_root = secDerivRoot_1;
else
triple_root = secDerivRoot_2;
simple_root = -b/a - 3*triple_root;
}
}
另一种方法,如果希望防止一个语句被更新,而另一个则不会,则如下所示:
#define SIMPLE_ROOT_CALC simple_root = -b/a - 3*triple_root
if(fabs(quartic_polynomial(a, b, c, d, e, secDerivRoot_1)) < 1e-6)
{
triple_root = secDerivRoot_1;
SIMPLE_ROOT_CALC;
}
else if (fabs(quartic_polynomial(a, b, c, d, e, secDerivRoot_2)) < 1e-6)
{
triple_root = secDerivRoot_2;
SIMPLE_ROOT_CALC;
}
else
printf("Something is wrong. No common root with its 2nd derivative. \n");
甚至是类似的东西
#define ROOT_CALC(x) triple_root = (x); simple_root = -b/a - 3*triple_root;
if(fabs(quartic_polynomial(a, b, c, d, e, secDerivRoot_1)) < 1e-6)
{
ROOT_CALC(secDerivRoot_1);
}
else if (fabs(quartic_polynomial(a, b, c, d, e, secDerivRoot_2)) < 1e-6)
{
ROOT_CALC(secDerivRoot_2);
}
else
printf("Something is wrong. No common root with its 2nd derivative. \n");
或者可能取决于与逻辑或运算符的评估短路:
{
double x;
if (! (((x = secDerivRoot_1), fabs(quartic_polynomial(a, b, c, d, e, secDerivRoot_1) < 1e-6)) || ((x = secDerivRoot_2), fabs(quartic_polynomial(a, b, c, d, e, secDerivRoot_2) < 1e-6) )) ) {
printf("Something is wrong. No common root with its 2nd derivative. \n");
} else {
triple_root = x;
simple_root = -b / a - 3 * triple_root;
}
}