1

给定一个数组,我必须在数组中打印必须为正且可被 2 整除的数字,如果条件不满足打印“未找到”仅一次。

我已经运行了我的代码,但得到了整个数组长度的“没有找到”消息。我如何对其进行编码,以便它只说一次?

这是我的代码:

numbers = [9 3 7 3];
i = 1;    
while i <= length(numbers)
    if numbers(i)>0 && mod(numbers(i),2) == 0
        disp(numbers(i))
    else
        disp('didint find')
        i = i + 1;
    end
end
4

1 回答 1

2
numbers = [9 3 7 3];
found = false; %This is a boolean flag used to see if we have found a number fitting the rules. If we find no number, found will be still false at the end of the loop

for i = 1:length(numbers) %A for loop is far more suited to this problem than your original while

    if numbers(i)>0 && mod(numbers(i),2) == 0

       disp(numbers(i))
       found = true;

    end
end
if ~found
    disp('Didn''t find');
end

但在 Matlab 中,您实际上可以不使用循环来执行此操作,实际上最好不要使用循环。试试下面的代码:

ind = numbers > 0 & mod(numbers,2) == 0;
if ~any(ind)
    disp('Didn''t find');
else    
    disp(numbers(ind)');
end
于 2013-05-02T11:53:14.700 回答