我正在编写二分法算法来查找多项式的根。我的代码的第二部分,它表示如果FP等于零或绝对值b-a
,它只会打破我猜的if语句。
我希望程序完全停止for循环(迭代)并返回p。最后,我想打印获得解决方案所需的迭代次数,但显然使用我的printf语句,它表明即使获得了根(零),程序也会继续执行。
关于如何停止整个机制并返回零的值和它所采用的确切迭代次数的任何想法?感谢
double computeroots(double a, double b, double epsilon, int MaxIter)
{
double FA = pow(a,4) -4*a + 1;
double FB = pow(b,4) - 4*b + 1;
double FP;
double p;
int i;
for(i=0;i<MaxIter;i++) {
if(FA * FB < 0) {
p = a + (b-a)/2;
FP = pow(p,4) - 4*p +1;
if(FP == 0 || abs(b-a) < epsilon) {
return p;
break;
} else if (FA * FP >0) {
a =p;
FA = FP;
} else {
b = p;
FB = FP;
}
i++;
}
}
printf("the number of iterations is : %d\n", i);
}
答案 0 :(得分:3)
您的printf
语句未被命中,因为您在return p;
语句之前有break
。 return
语句会立即退出函数。
您需要将return
语句移至printf
之后,或将printf
移至return
之前:
if(FP == 0 || abs(b-a) < epsilon)
{
printf("the number of iterations is : %d\n", i);
return p;
}
...
printf("failed to converge after %d iterations\n", i);
return p;
}
答案 1 :(得分:1)
如果您有return
语句,那么您的break
语句就没用了。返回退出函数的范围并返回给调用者,因此之后不再执行指令。
所以这个:
return p;
break;
应该成为:
printf("the number of iterations is : %d\n", i);
return p;
如果您发现退出条件未正确选择,我猜它更像是一个有限精度问题。您正在检查FP == 0
,但FP
是double
,因此您必须在FP
足够接近0时停止,而不是在它完全相等时停止。例如:abs(FP) < epsilon
。
答案 2 :(得分:0)
你可以返回一个双精度数组,其中第一个元素是结果,第二个元素是迭代次数。
或者,您将对变量的引用传递给函数,并将其赋值给它,如下所示:
double compute_something(int param1, int param2, int* iterations) {
// your code ...
// when you want to return, use this:
*iterations = 5;
return 1.23;
// your code ...
}
int iter;
double result = compute_something(1,2, &iter);
在此之后,结果包含结果,并且它包含您存储的迭代次数。 这个解决方案可能会更好,因为你没有将迭代次数(显然是一个整数)作为double返回。
答案 3 :(得分:0)
当您需要返回多个值时,可以使用out-arguments来执行此操作。将您的功能更改为
double computeroots(double a, double b, double epsilon, int MaxIter, int *numIterations)
这样称呼:
int numIter;
soln = computeroots(a, b, epsilon, MaxIter, &numIter);
并且在你的函数中,在返回之前,添加:
*numIterations = i;
答案 4 :(得分:0)
合并所有必要的mods / s:
double computeroots(
double a,
double b,
double epsilon,
size_t MaxIter,
size_t * pNumIter
)
{
double FA = pow(a,4) -4*a + 1;
double FB = pow(b,4) - 4*b + 1;
double FP;
double p = NaN;
size_t i;
for(i=0; i<MaxIter; ++i) {
if(FA * FB < 0) {
p = a + (b-a)/2;
FP = pow(p,4) - 4*p +1;
if(FP == 0 || abs(b-a) < epsilon) {
break;
} else if (FA * FP >0) {
a =p;
FA = FP;
} else {
b = p;
FB = FP;
}
}
}
*pNumIter = i;
printf("the number of iterations is : %z\n", *pNumIter);
return p;
}
这样称呼:
double a, b, epsilon;
size_t sizeMax, sizeIterations;
... /* some initialisations here */
double d = computeroots(a, b, epsilon, sizeMax, &sizeIterations);
关于mod / s的说明:
return
int
更改为size_t
,因为unsigned
类型更适合计数器size_t
变量的引用以返回迭代次数i