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 visualización (últimos 30 días)
Mostrar comentarios más antiguos
%% 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
0 comentarios
Respuestas (1)
darova
el 19 de Sept. de 2019
Editada: darova
el 19 de Sept. de 2019
2 comentarios
Steven Lord
el 19 de Sept. de 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
el 19 de Sept. de 2019
Select the code, right-click, and select Smart Indent
Didn't know that. THanks
Ver también
Categorías
Más información sobre Testing Frameworks en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!