📄 calc_root.m
字号:
% script file calc_root.m
%
% purpose:
% This program solves for the roots of a quadratic equation
% of the form a*x^2+b*x+c=0.It calcaulates the answers of
% roots the equation posseses.
%
% Define variables:
% a coefficient of x^2
% b coefficient of x
% c constant term
% x1 first root of the equation
% x2 second root of the equation
disp('This program solves for the roots of a quadratic equation');
disp('of the form a*x^2+b*x+c=0');
a=input('Enter the coefficient A:');
b=input('Enter the coefficient B:');
c=input('Enter the coefficient C:');
discriminant=b^2-4*a*c;
%如果判别式大于0
%则根据二元方程的公式得出两个不同的实数解
if discriminant>0
x1=(-b+sqrt(discriminant))/(2*a);
x2=(-b-sqrt(discriminant))/(2*a);
%在命令窗口显示求解结果
disp('This equation has two real roots');
fprintf('x1=%f\n',x1);
fprintf('x2=%f\n',x2);
%当判别式等于0,则返回两个相同的实数根
elseif discriminant==0
x1=-b/(2*a);
disp('This equation has two identical roots');
fprintf('x1=x2=%f\n',x1);
%当判别式小于0,则返回两个虚根
else
real_part=-b/(2*a);
image_part=sqrt(abs(discriminant))/(2*a);
disp('This equation has two complex roots');
fprintf('x1=%f+i%f\n',real_part,image_part);
fprintf('x2=%f-i%f\n',real_part,image_part);
end
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -