0

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

部分代码:

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

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

4

1 回答 1

0

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

rowv我创建了两个数组:row坐标和colv坐标col

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

% 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
于 2016-04-23T23:53:17.790 回答