Displaying complex roots of quadratic equation

조회 수: 19 (최근 30일)
Valentina Sandberg
Valentina Sandberg 2018년 3월 7일
답변: Roger Stafford 2018년 3월 8일
This is my code.
a = input ('enter a: ');
b = input ('enter b: ');
c = input ('enter c: ');
xmin = input ('enter xmin: ');
xmax = input ('enter xmax: ');
step = (xmax - xmin)/100;
x = xmin : step : xmax;
y = a.*x.^2 + b.*x + c;
plot (x,y);
grid on;
xlabel ('x') ;
ylabel ('y');
xtickangle (45);
title (['Plot of f(x) = ', num2str(a), 'x.^2 + ', num2str(b), 'x + ', num2str(c)]);
D = b^2 - 4*a*c;
if D >= 0
x1 = (-b + sqrt (D)) / (2*a);
x2 = (-b - sqrt (D)) / (2*a);
fprintf ('Real zeros: %g, %g, \n', x1, x2)
fprintf ('Factored Form: f(x) = (x - %g)(x - %g) \n', x1, x2)
else
x1 = (-b + sqrt (D)) / (2*a);
x2 = (-b - sqrt (D)) / (2*a);
fprintf ('Complex Zeroes: %g, %g, \n', x1, x2)
fprintf ('Factored Form: f(x) = (x - (%g))(x - (%g)) \n', x1, x2)
end
When I have a quadratic with complex roots, the last line of the code only displays the real part of the root. Why? How can I change it so it displays both the real and imaginary part?

답변 (1개)

Roger Stafford
Roger Stafford 2018년 3월 8일
On that 'else' part you need to find the two values real(x1) and imag(x1) as well as these two for x2. Then provide a display of all four quantities in each of your 'fprintf' lines. You might have something like this:
fprintf('Complex Zeros: %g + i*%g, %g + i*%g\n',real(x1),imag(x1),real(x2),imag(x2))

태그

Community Treasure Hunt

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

Start Hunting!

Translated by