声振论坛

 找回密码
 我要加入

QQ登录

只需一步,快速开始

查看: 1752|回复: 0

[编程技巧] 规范MATLAB编程实例——求解一元二次方程

[复制链接]
发表于 2016-3-4 15:39 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?我要加入

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

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



    程序代码:​

% 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);​



     运行结果:​

                               
登录/注册后可看大图



  

   要点说明:

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

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

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

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

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



    涉及到的命令:​

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

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

    sqrt         :  平方根运算

转自:http://blog.sina.com.cn/s/blog_a0d5c2aa0102vx2g.html
回复
分享到:

使用道具 举报

您需要登录后才可以回帖 登录 | 我要加入

本版积分规则

QQ|小黑屋|Archiver|手机版|联系我们|声振论坛

GMT+8, 2024-5-18 09:58 , Processed in 0.056147 second(s), 17 queries , Gzip On.

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

快速回复 返回顶部 返回列表