How to stop quadratic formula calculator from giving inverse outputs?
2 次查看(过去 30 天)
显示 更早的评论
Hi, I'm doing a worksheet based around matlab which involved solving quadratic formulas. I probably overcomplicated it and now made a calculator that keeps giving the inverse of my expected answer, could anyone help please?
for k = 1 : 7
disp ( ' For the equation ax^2 + bx + c ' )
a = input ( ' Enter a; ' );
b = input ( ' Enter b; ' );
c = input ( ' Enter c; ' );
D = ( b^2 ) - ( 4 * a * c );
if D < 0
fprintf ( ' \n The equation has no real roots . \n\n ')
elseif D == 0
root = -b / ( 2 * a );
fprintf ( ' \nThe equation has one root, \n ' )
fprintf ( ' %.7f\n\n ' , root )
else
r1 = ( - b + sqrt ( D ) ) / ( 2 * a ) ;
r2 = ( - b - sqrt ( D ) ) / ( 2 * a ) ;
fprintf ( '\n The equation has two roots, \n ' )
fprintf ( ' %.7f and %.7f\n\n ' , r1 ,r2 )
end
end
For the equation ax^2 + bx + c
Enter a;
1
Enter b;
9
Enter c;
14
The equation has two roots,
-2.0000000 and -7.0000000
For the equation ax^2 + bx + c
Enter a;
1
Enter b;
-3
Enter c;
-18
The equation has two roots,
6.0000000 and -3.0000000
回答(1 个)
John D'Errico
2024-5-30
编辑:John D'Errico
2024-5-30
The roots of the quadratic you supply are indeed 6 and -3.
roots([1 -3 -18])
So your code worked correctly.
If you expected something else, then it is your expectations that are wrong, not your code.
Anyway, perhaps I should point out that a cute feature of polynomial equations in that if you reverse the sequence of the cofficients, thus as here...
roots([-18 -3 1])
then the computed roots will be the inverses of the true roots. And that is what I think has happened to you in some way. This would be true for any order polynomial, in fact.
Perhaps that is what you did at some point in your code, or maybe in your spreadsheet, you provided the coefficients in the reverse order. Can we know what you actually did wrong, since your code works correctly? Only da shadow know, but I'm going to bet, that IF you have gotten the inverse of the expected roots, then somewhere, somehow, you flipped the sequence of the coefficients. I'm not da shadow though.
3 个评论
John D'Errico
2024-6-10
Lol. An intersting fact about an equation like
x^2 + 14*x + 9
is if ALL of the coefficients are positive, then there can NEVER be any positive real roots. Any real roots must either be zero or negative, and zero only happens if there is a zero constant term.
(You can prove that easily enough if you think about it.) For a positive root to exist, at least SOME of the coefficients must be negative.
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!