我正在構建一個戰艦游戲,我使用以下代碼編輯一個 6 x 6 的數字來表示放置在其中的船只。
top_left_grid= input(.....)
orientation = input(please enter v or h for vertical or horizontal)
if top_left_grid == 1
if orientation == 'v'
% write code to make changes on figure
else
%write code to make changes on figure
end
end
now sometimes when a specific top_left-grid and orientation are entered the ship would be out of bounds, for example when grid 6 and h are chosen, the ship will be out of bound.
那么如何讓程式允許用戶在輸入 6 和 h 后重試。
我在嘗試這樣的事情,
if top_left_grid == 6
if orientation == 'v'
% write code to make changes on figure
while
else
top_left_grid= input('try again')
end
end
end
但沒有這樣的作業,所以任何關于我能做什么的建議
uj5u.com熱心網友回復:
例如,您可以使用“標志”來實作這種嘗試直到成功的邏輯
validChoice = false; % set flag up front, false so we enter the loop at least once
while ~validChoice
top_left_grid = input('Enter top-left grid square number','s');
top_left_grid = str2double( top_left_grid );
orientation = input('Enter v or h for vertical or horizontal','s');
if (top_left_grid==6 && strcmpi(orientation,'h'))
% This is invalid
disp( 'Invalid choice, cannot fit ship in chosen location, try again...' );
else
% Input is OK, set the flag to true so the loop exits
validChoice = true;
end
end
% To get this far there must be a valid choice
% Do whatever you want with "top_left_grid" and "orientation" now...
您可以在內部if-elseif-else塊中包含其他有效性測驗。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/401346.html
標籤:MATLAB
上一篇:MATLAB中的前向歐拉法
