“数制转换”对话框
本文利用MATLAB设计了,“数制转换”对话框
参考书籍为《MATLAB程序设计与用用》
界面为下图所示:
该对话框可将用户输入的十进制输转换为想要的2~16进制数
MATLAB主程序代码如下:
%hf是界面,color为设置界面颜色
hf=figure('Color',[0,1,1],'Position',[300,300,400,200],'Name','tt牌数制转换',...
'Numbertitle','off','Menubar','none');
%%
%输入边框设置和文字说明
uicontrol(hf,'Style','Text','Position',[80,160,40,20],'Horizontal','center',...
'String','输入框','Back',[0,1,1]);%back为背景色
uicontrol(hf,'Style','Frame','position',[20,65,165,90],'Back',[1,1,0]);
uicontrol(hf,'Style','Text','position',[25,110,85,25],'Back',[1,1,0],...
'Horizontal','center','String','十进制数');
uicontrol(hf,'Style','Text','position',[25,75,85,25],'Back',[1,1,0],...
'Horizontal','center','String','2~16进制数');
%设置编辑框,用于用户输入字符
he1=uicontrol(hf,'Style','Edit','position',[100,115,60,25],'Back',[0,1,0]);
he2=uicontrol(hf,'Style','Edit','position',[100,80,60,25],'Back',[0,1,0]);
%%
%输出边框
uicontrol(hf,'Style','Text','Position',[280,160,40,20],'Horizontal',...
'center','String','输出框','Back',[0,1,1]);%text为静态文本
uicontrol(hf,'Style','Frame','position',[215,65,165,90],'Back',[1,1,0]);%frame为边框
ht=uicontrol(hf,'Style','Text','position',[255,95,90,30],'Back',[0,1,0]);
%%
%tradec是进制转换子函数
COMM=['n=str2num(get(he1,''string''));','b=str2num(get(he2,''string''));',...
'dec=tradec(n,b);','set(ht,''string'',dec);'];
uicontrol(hf,'Style','Push','Position',[55,20,90,25],'String','转换','Call',COMM);
uicontrol(hf,'Style','Push','Position',[255,20,90,30],'String','退出','Call','close(hf)');
子函数tradec代码如下(采用的是除k取余法转换进制)
function dec = tradec(n,b)
ch1='0123456789ABCDEF';
k=1;
while n~=0
p(k)=rem(n,b);
n=fix(n/b);
k=k+1;
end
k=k-1;
strdec=' ';
while k>=1
kb=p(k);
strdec=strcat(strdec,ch1(kb+1:kb+1));
k=k-1;
end
dec=strdec;
end
结果检验:
当输入了十进制10,转换为1010,结果正确