Wenn ich die while
entferne und eine Bedingung in der if, else if, else
auswähle, kann ich ein Ergebnis erhalten. Aber wenn ich die while
Zirkulation in die Funktion auflöse, passiert eine Endlosschleife. Bitte finde heraus, wo das Problem liegt.Was stimmt nicht mit dieser Zirkulation?
#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;
}
Warum haben Sie dies als C++ markiert? –
Haben Sie bereits versucht, den Wert von 'diff' am Ende jeder Schleife auszudrucken? – JVApen
Gleichheit in Fließkommazahlen ist keine gute Idee - siehe [Was jeder Informatiker über Gleitkommaarithmetik wissen sollte] (https://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html) –