function result = calculator()
disp('请选择操作:');
disp('1. 加法');
disp('2. 减法');
disp('3. 乘法');
disp('4. 除法');
choice = input('输入您的选择(1/2/3/4): ');
num1 = input('输入第一个数: ');
num2 = input('输入第二个数: ');
switch choice
case 1
result = num1 + num2;
disp(['结果为: ', num2str(result)]);
case 2
result = num1 - num2;
disp(['结果为: ', num2str(result)]);
case 3
result = num1 * num2;
disp(['结果为: ', num2str(result)]);
case 4
if num2 ~= 0
result = num1 / num2;
disp(['结果为: ', num2str(result)]);
else
disp('除数不能为 0!');
end
otherwise
disp('无效的选择!');
end
end
function calculator_gui
fig = figure('Name', 'Calculator', 'Position', [500, 500, 300, 200]);
% 输入框 1
edit1 = uicontrol('Style', 'edit', 'Position', [50, 50, 100, 20]);
% 输入框 2
edit2 = uicontrol('Style', 'edit', 'Position', [50, 80, 100, 20]);
% 操作选择下拉菜单
popupmenu1 = uicontrol('Style', 'popupmenu', 'String', {'加法', '减法', '乘法', '除法'}, 'Position', [160, 50, 80, 20]);
% 计算按钮
button1 = uicontrol('Style', 'pushbutton', 'String', '计算', 'Position', [100, 120, 80, 20], 'Callback', @calculate);
% 结果输出框
edit3 = uicontrol('Style', 'edit', 'Position', [50, 150, 200, 20]);
function calculate(source, eventdata)
num1 = str2double(get(edit1, 'String'));
num2 = str2double(get(edit2, 'String'));
choice = get(popupmenu1, 'Value');
switch choice
case 1
result = num1 + num2;
case 2
result = num1 - num2;
case 3
result = num1 * num2;
case 4
if num2 ~= 0
result = num1 / num2;
else
result = '除数不能为 0';
end
end
set(edit3, 'String', num2str(result));
end
end