我有以下 C 代码。计算simple_root的语句出现了两次。我想知道是否有更好的方法来组织代码,使语句只出现一次。
如果将simple_root放在最后一个else之后,则存在出错的风险,例如前两个条件不匹配。如果我错了,请纠正我。
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");
最佳答案
您在评论中遗漏了一些内容
If putting the simple_root after the last else, there is a risk of error, e.g. the previous two conditions doesn't match
情况已经如此 - 如果您不匹配这两个,则 triple_root
和 simple_root
尚未设置。我不确定在这段代码之后如何使用它们或者您的错误处理是什么。您可以在 printf
语句后立即返回,也可以将 triple_root
设置为 NaN
。
然后您可以将 simple_root 方程移至 if
语句下方。或者,您可以将其放入函数中。一行函数就可以了,可以让代码更容易理解。
关于C: 方程式只出现一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51392832/