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 次查看(过去 30 天)
显示 更早的评论
%% 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 个评论
回答(1 个)
darova
2019-9-19
编辑:darova
2019-9-19
2 个评论
Steven Lord
2019-9-19
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.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Testing Frameworks 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!