How can I Write a program that determines how many real roots are expected out of the quadratic equation (ax2 + bx+ c = 0) with corresponding inputs. When a user runs the file it should ask for the values of the constants a, b, and c.

1 vue (au cours des 30 derniers jours)
%% Problem 3
%Finding the real roots of quadratic equation
%a*(x^2) + b*x + c = 0
a = input('\nPlease enter a value for the constant a:');
b = input('\nPlease enter a value for the constant b:');
c = input('\nPlease enter a value for the constant c:');
p = [a b c];
D = b^2 - 4*a*c %Number of Roots
if D > 0
r1=(-b+sqrt(b^2-4*a*c))/2*a;
r2=(-b-sqrt(b^2-4*a*c))/2*a;
fprintf('The equation has 2 roots: %i, %i',r1,r2);
if D < 0
disp('The equation has no real roots!')
else
r1=(-b+sqrt(b^2-4*a*c))/2*a;
r2=(-b-sqrt(b^2-4*a*c))/2*a;
fprintf('\nThe equation has 1 root: %i',r1);
end
end

Réponses (1)

darova
darova le 19 Sep 2019
Modifié(e) : darova le 19 Sep 2019
I made a printscreen for you
From this page: LINK
Look carefully on your if statement
  2 commentaires
Steven Lord
Steven Lord le 19 Sep 2019
Good catch. Another way to detect this incorrect nesting of if statements is to smart indent the code. Select the code, right-click, and select Smart Indent from the context menu. That makes it clear that there's no way to reach the "The equation has no real roots" disp statement as written.
One efficiency suggestion for John Nowak: you compute D before your if statement, then you recompute it as part of computing r1 and r2 inside the body of the if. Why not just reuse the D you've already computed? Since a, b, and c are going to be scalars (you don't check, but since this is a homework assignment your professor probably isn't going to try to trip you up like that) this doesn't save you much time for this assignment. But if in future assignments you're working with larger data sets, avoiding computing the same quantity multiple times might save a lot of effort.
darova
darova le 19 Sep 2019
Select the code, right-click, and select Smart Indent
Didn't know that. THanks

Connectez-vous pour commenter.

Catégories

En savoir plus sur Testing Frameworks dans Help Center et File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by