如何在条件中使用用户输入 (MATLAB)
How to use user input in a conditional (MATLAB)
我制作了一个带有用户输入的简单球体计算器:
clc
%Ask For Radius
radius = input ('What is the radius of your sphere?');
%Calculate Volume Using Radius
vlm = (4/3) * pi * radius^3 ;
%Return Radius
fprintf('The volume of your sphere is %4.2f inches cubed\n', vlm)
但我决定更进一步,让用户可以选择问一个又一个,直到他们不想再问了。但是我被卡住了,因为我不知道如何接受这个用户输入:
again = input ('Do You Want To Find The Volume Of A Sphere?','s')
并将其应用于条件语句,例如 if else 语句。以下是我到目前为止的想法:
if again = yes
%Ask For Radius
%Insert VolumeOfSphere.m
else
fprintf('Ok, Just run Me Again If You Want To Calculate Another Sphere')
%Add An End program Command
end
非常感谢任何正确方向的帮助或提示。
excaza 是对的,while 循环听起来正是您所需要的。一个基本的实现可能是:
clc; clear;
while true
%Ask For Radius
radius = input ('What is the radius of your sphere? ');
%Calculate Volume Using Radius
vlm = (4/3) * pi * radius^3 ;
%Return Radius
fprintf('The volume of your sphere is %4.2f inches cubed\n', vlm)
% Ask if they want to run again
run_again = input('\nWould you like to run again? Y or N: ', 's');
% Deal with their answer
if strcmpi(run_again, 'Y')
% do nothing, let the loop keep running
elseif strcmpi(run_again, 'N')
break % this will break out of the while loop and end the program
else
% assume they meant Y, and send them back to the start
end
end
我制作了一个带有用户输入的简单球体计算器:
clc
%Ask For Radius
radius = input ('What is the radius of your sphere?');
%Calculate Volume Using Radius
vlm = (4/3) * pi * radius^3 ;
%Return Radius
fprintf('The volume of your sphere is %4.2f inches cubed\n', vlm)
但我决定更进一步,让用户可以选择问一个又一个,直到他们不想再问了。但是我被卡住了,因为我不知道如何接受这个用户输入:
again = input ('Do You Want To Find The Volume Of A Sphere?','s')
并将其应用于条件语句,例如 if else 语句。以下是我到目前为止的想法:
if again = yes
%Ask For Radius
%Insert VolumeOfSphere.m
else
fprintf('Ok, Just run Me Again If You Want To Calculate Another Sphere')
%Add An End program Command
end
非常感谢任何正确方向的帮助或提示。
excaza 是对的,while 循环听起来正是您所需要的。一个基本的实现可能是:
clc; clear;
while true
%Ask For Radius
radius = input ('What is the radius of your sphere? ');
%Calculate Volume Using Radius
vlm = (4/3) * pi * radius^3 ;
%Return Radius
fprintf('The volume of your sphere is %4.2f inches cubed\n', vlm)
% Ask if they want to run again
run_again = input('\nWould you like to run again? Y or N: ', 's');
% Deal with their answer
if strcmpi(run_again, 'Y')
% do nothing, let the loop keep running
elseif strcmpi(run_again, 'N')
break % this will break out of the while loop and end the program
else
% assume they meant Y, and send them back to the start
end
end