检查用户 MATLAB 是否重复输入坐标



谁能帮我编写代码来检查用户是否输入了两次相同的坐标?

部分代码:

rc = input('Enter your next move [row space column]: ');
              row = rc(1); %users coordinates 
              col = rc(2);
                           if row<0 || col<0
                           disp('Please enter positive coordinates');
                           rc = input('Enter your next move [row space column]: ');
                           row = rc(1); 
                           col = rc(2);
                           end
                           if row>size || col>size
                           disp('Please enter cordinates with in the game board');
                           rc = input('Enter your next move [row space column]: ');
                           row = rc(1);
                           col = rc(2);
                           end

我已经检查了正值和太大的值,但现在我想检查以确保用户没有两次输入相同的坐标,以及他们是否确实显示错误消息。任何帮助不胜感激谢谢

正如我在注释部分已经提到的,为了确保用户不会两次输入相同的坐标,您应该将每对有效坐标存储在数组中,以便下次用户输入一对新坐标时,您可以检查它们是否已经存在。

我创建了两个数组:rowv 用于row坐标,colv 用于col坐标。

然后,我使用逻辑运算符any&,结合==关系运算符实现了以下while条件:

% Check that the point is not repeated.
while any((rowv == row) & (colv == col))

因此,只要用户重复输入坐标,他/她就会被要求重试,直到输入有效的对。

以下代码是一个完整的工作示例,因此您可以立即对其进行测试:

% Game board size.
size = 4;
% Ask for number of points.
n = input('Number of points: ');
% Preallocate arrays with -1.
rowv = -ones(1,n);
colv = -ones(1,n);
% Iterate as many times as points.
for p = 1:n
    % Ask for point coordinates.
    rc = input('Enter your next move [row space column]: ');
    row = rc(1);
    col = rc(2);
    % Check that coordinates are positive.
    while row<0 || col<0
        disp('Please enter positive coordinates');
        rc = input('Enter your next move [row space column]: ');
        row = rc(1);
        col = rc(2);
    end
    % Check that coordinates are within the game board.
    while row>size || col>size
        disp('Please enter cordinates within the game board');
        rc = input('Enter your next move [row space column]: ');
        row = rc(1);
        col = rc(2);
    end
    % Check that the point is not repeated.
    while any((rowv == row) & (colv == col))
        disp('Coordinates already exist. Please enter a new pair of cordinates');
        rc = input('Enter your next move [row space column]: ');
        row = rc(1);
        col = rc(2);
    end
    % The point is valid.
    % Store coordinates in arrays.
    rowv(p) = rc(1);
    colv(p) = rc(2);
end

相关内容

  • 没有找到相关文章

最新更新