gpt4 book ai didi

c++ - 这个循环有什么问题吗?

转载 作者:行者123 更新时间:2023-11-30 21:28:54 25 4
gpt4 key购买 nike

如果我删除 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;
}

最佳答案

首先那是c而不是c++!如果你返回 diff 你每次都会得到一个小于 0.001 的值作为解决方案。我认为你应该返回x3。如果你问 fun(x3) == 0 fun(x3) 必须完全等于 0。在大多数情况下,使用 float 你永远无法达到这一点。最好这样做:

        funx3=fun(x3);

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

这也不是在所有情况下都有效。要解决这个问题,请在整个程序中使用 double 。您还将获得更多的小数位。我不完全确定所有小数位是否正确。也许你不应该削减一个时代。

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

关于c++ - 这个循环有什么问题吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36821781/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com