一元二次求解matlab程序,规范MATLAB编程实例——求解一元二次方程

好的程序应当具有较好的可读性,良好的可读性可以使得编程者和使用者读程序的时候顺畅很多。如果程序编得很混乱,有可能当编程者久隔多日再一次打开程序时,就读不懂原来的程序了。

下面从一个简单的实例出发,说明如何规范编程,增强可读性。​

程序代码:​

% purpose:solves for the roots of a quadratic equation of the

form

% a*x^2+b*x+c=0.

%

% date:160226

% programmer:wf

%

% define variables:

% a

--coefficient of x^2 term of equation

% b

--coefficient of x term of equation

% c

--constant term of equation

% deta

--deta of the equation

% x1,x2

--solutions

%

% prompt the user for the coefficients of the equation

disp('solve the equation of the from a*x^2+b*x+c=0');

a=input('a=');

b=input('b=');

c=input('c=');​

% calculate deta

deta=b^2-4*a*c;​

% solve the equation

x1=(-b+sqrt(deta))/2/a;

x2=(-b-sqrt(deta))/2/a;

disp('x1=');

disp(x1);

disp('x2=');

disp(x2);​

运行结果:​

a4c26d1e5885305701be709a3d33442f.png

要点说明:

1.“%”后面的内容是注释。​

2.在程序的开头写明程序的功能即purpose​

3.接下来写明程序的编写日期及编写者​

4.然后写明定义的所有变量的含义(这一步很重要)​

5.最后才是程序的主体,即执行的语句。​

涉及到的命令:​

input​

:用于读取用户从键盘上输入的值

disp

:用于把内容输出在屏幕上​

sqrt:  平方根运算

  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值