这种流通有什么问题?

时间:2016-04-24 10:09:39

标签: c++ c

如果我删除while并在if, else if, else中选择一个条件,我就可以得到结果。但是当我将while循环添加到函数solve中时,会发生无限循环。请弄清楚问题出在哪里?

#include<stdio.h>
#include<math.h>
int a, b, c, d;
float fun(float x);
float solve(void);

int main()
{
    printf("Put in the coefficient of the equation:\n");
    scanf("%d", &a);
    scanf("%d", &b);
    scanf("%d", &c);
    scanf("%d", &d);

    float ans = solve();

    printf("A solve for the equation:x=%.3f", ans);

    return 0;
}

float fun(float x)
{
    float value = a * x * x * x + b * x * x + c * x + d;

    return value;
}

float solve(void)
{
    float x1 = -100, x2 = 100, x3;
    float diff = fabs(fun(x1) - fun(x2));
    while (diff > 0.001)
    {
        x3 = (x1 * fun(x2) - x2 * fun(x1)) / (fun(x2) - fun(x1));

        if (fun(x3) == 0)
        {
            x1 = x3;
            x2 = x3;
        }
        else if ((fun(x3) * fun(x1)) < 0)
        {
            x2 = x3;
        }
        else
        {
            x1 = x3;
        }

        diff = fabs(fun(x1) - fun(x2));
    }

    return diff;
}

1 个答案:

答案 0 :(得分:0)

首先,那不是c ++ !!! 如果你返回差异你每次得到一个小于0.001的值作为解决。 我想你应该回来x3。 如果你问fun(x3) == 0 fun(x3)必须完全等于零。在大多数情况下,你永远不会达到那个浮点数。最好这样做:

        funx3=fun(x3);

        if (funx3 == 0.0 || funx3>0.0 &&funx3<0.001 || funx3<0.0 && funx3>-0.001 )
        {
            x1 = x3;
            x2 = x3;
        }

此外,在所有情况下都不会起作用。为了解决这个问题,请在整个程序中使用双打。您还将获得更多小数位。我不完全确定所有小数位是否正确。也许你可以削减一个人。

#include<stdio.h>
#include<math.h>
int a, b, c, d;
double fun(float x);
double solve(void);

int main()
{
    printf("Put in the coefficient of the equation:\n");
    scanf("%d", &a);
    scanf("%d", &b);
    scanf("%d", &c);
    scanf("%d", &d);

    float ans = solve();

    printf("A solve for the equation:x=%.8f", ans);

    return 0;
}

double fun(float x)
{
    double value = a * x * x * x + b * x * x + c * x + d;

    return value;
}

double solve(void)
{
    double x1 = -100, x2 =100, x3;
    double diff = fabs(fun(x1) - fun(x2));
    double funx3;
    while (diff > 0.0000001)
    {
        x3 = (x1 * fun(x2) - x2 * fun(x1)) / (fun(x2) - fun(x1));

        funx3=fun(x3);

        if (funx3 == 0.0 || funx3>0.0 &&funx3<0.0000001 || funx3<0.0 && funx3>-0.0000001 )
        {
            x1 = x3;
            x2 = x3;
        }
        else if ((fun(x3) * fun(x1)) < 0.0)
        {
            x2 = x3;
        }
        else
        {
            x1 = x3;
        }

        diff = fabs(fun(x1) - fun(x2));
    }

    return x3;
}