简体   繁体   English

如何突破C语言的循环

[英]How to break out of a loop in C

I'm writing a bisection method algorithm to find the roots of polynomials. 我正在编写一个二等分方法算法来查找多项式的根。 The second part of my code where it says if variable FP is equal to zero or absolute value of ba it just breaks the if statement I guess. 我的代码的第二部分说,如果变量FP等于0或ba绝对值,它将破坏if语句。

I want the program to stop the for loop (iteration) entirely and return p. 我希望程序完全停止for循环(迭代)并返回p。 And at the end I want to print the number of iteration it took to get the solution but apparently using my printf statement it shows that the program keeps executing even thought the root (zero) is obtained. 最后,我想打印获得解决方案所需的迭代次数,但显然使用我的printf语句,它表明程序即使在获得根(零)的情况下仍继续执行。

Any ideas on how to stop the whole mechanism and return both the value of p which is zero and the exact number of iteration it took? 关于如何停止整个机制并返回p的值为零(它的值为零)和所花费的确切迭代次数的任何想法? Thanks 谢谢

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);
}

Your printf statement isn't hit because you have a return p; 您的printf语句未命中,因为您的return p;值为return p; before the break statement. break语句之前。 A return statement immediately exits the function. return语句立即退出该函数。

You need to move the return statement to after the printf , or move the printf before the 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;
}

If you have a return statement, then your break statement is useless. 如果您有return语句,则break语句将无用。 The return exits the scope of the function and goes back to the caller so no more instructions are executed afterward. 返回值将退出函数范围,并返回到调用方,因此以后不再执行任何指令。

So this: 所以这:

return p;
break;

should become: 应该变成:

printf("the number of iterations is : %d\n", i);
return p;

If you see that the exit condition is not correctly chosen I'd guess it's more a finite precision problem . 如果您发现出口条件选择不正确,我想那可能是一个有限精度问题 You are checking FP == 0 but FP is a double so you have to stop when FP is enough close to 0 not when it is exactly equal. 您正在检查FP == 0但是FPdouble因此当FP足够接近0而不是完全相等时,您必须停止。 Eg: abs(FP) < epsilon . 例如: abs(FP) < epsilon

When you need to return more than one value, you can do it with out-arguments. 当您需要返回多个值时,可以使用外参数。 Change your function to 将功能更改为

double computeroots(double a, double b, double epsilon, int MaxIter, int *numIterations)

call it like this: 这样称呼它:

int numIter;
soln = computeroots(a, b, epsilon, MaxIter, &numIter);

and in your function, just before returning, add: 在返回之前,在函数中添加:

*numIterations = i;

To merge all necessary modifications: 合并所有必要的修改:

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;
}

Call it like so: 这样称呼它:

double a, b, epsilon;
size_t sizeMax, sizeIterations;

... /* some initialisations here */

double d = computeroots(a, b, epsilon, sizeMax, &sizeIterations);

Notes on modifications: 修改说明:

  • removed misplaced return 删除错放的return
  • added missing return at the end 最后添加了缺少的回报
  • changed int s to be size_t , as an unsigned type suits better for counters int s更改为size_t ,因为unsigned类型更适合计数器
  • added reference to additional size_t variable to return number of iterations 添加对附加size_t变量的引用以返回迭代次数
  • removed second incrementation of i 删除了i第二个增量

You can return an array of doubles, where the first element is the result, and the second one is the number of iteration. 您可以返回一个双精度数组,其中第一个元素是结果,第二个元素是迭代次数。

Or, you pass the reference to a variable to the function, and assign to it, like this: 或者,您将对变量的引用传递给函数,然后分配给它,如下所示:

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);

After this, result contains the result, and iter the number of iterations that you stored. 此后,结果包含结果,并迭代您存储的迭代次数。 This solution would likely be better, because you are not returning the number of iterations (which is clearly an integer number) as a double. 此解决方案可能会更好,因为您不会将迭代次数(显然是整数)返回为双精度。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM