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

답변 (1개)

darova
darova 2019년 9월 19일
편집: darova 2019년 9월 19일
I made a printscreen for you
From this page: LINK
Look carefully on your if statement
  댓글 수: 2
Steven Lord
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.
darova
darova 2019년 9월 19일
Select the code, right-click, and select Smart Indent
Didn't know that. THanks

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Testing Frameworks에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by