如何在条件(MATLAB)中使用用户输入

时间:2018-01-19 17:21:21

标签: matlab conditional user-input

我用一个用户输入做了一个简单的球形计算器:

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和if语句。这是我到目前为止所提出的:

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

提前非常感谢任何正确方向的帮助或提示。

1 个答案:

答案 0 :(得分:1)

excaza是对的,一段时间的循环听起来就像你需要的那样。这个的基本实现可能是:

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