在下面的代码中,我检查第一个字母是否在单词词典中,以及单词的长度是否匹配。如果是,请返回单词。否则,返回错误声明。
words = {'apple', 'banana', 'bee', 'salad', 'corn', 'elephant', 'pterodactyl'};
user_letter_input = input('Please enter the first letter of a word: ', 's');
user_num_input = input('Please enter how long you would like the word to be: ');
for i = words
if ((i{1}(1) == user_letter_input) && (length(i{1}) == user_num_input))
result = i;
else
result = 0;
end
end
if (result == 0)
disp('There are no matching words');
else
disp(['Your new word is: ' result]);
end
如果我为第一个输入键入i
而第二个输入键入'apple'
,则比较会返回a
为5
。
但是,当我尝试查看if (result == 0)
时,即使result
不为0,它也不会显示新词。
有人可以帮我解决这个问题吗?
答案 0 :(得分:2)
每次通过for循环都会覆盖result
。 result
在循环之后唯一的时间是0,words
中的最后一个单词是否符合您的条件。
我建议将匹配的单词存储在单独的单元格数组中,或者使用布尔数组来指示哪些单词匹配。在我看来,使用布尔值更好,因为它占用更少的内存并且不会重复数据。
words = {'apple', 'banana', 'bee', 'salad', 'corn', 'elephant', 'pterodactyl'};
user_letter_input = input('Please enter the first letter of a word: ', 's');
user_num_input = input('Please enter how long you would like the word to be: ');
isMatch = false(size(words));
for k = 1:numel(words)
word = words{k};
isMatch(k) = word(1) == lower(user_letter_input) && ...
numel(word) == user_num_input;
end
if ~any(isMatch)
disp('There are no matching words');
else
disp(['Your matching words are:', sprintf(' %s', words{isMatch})]);
end
另外,作为旁注不要像那样在for循环中使用单元格数组。这导致了很多混乱。还avoid using i
as a loop variable。
答案 1 :(得分:1)
每次词典中的单词不匹配时,您都会覆盖result
。唯一可行的方法是,如果最后一个单词匹配。您需要更改result
和循环的初始化:
result = 0; %// assume that no words match
for i = words
if (....
result = 1; %// we found a match... record it
end
%// no else! If we get no match, result will already be 0
end
答案 2 :(得分:0)
您可以使用标志来检测是否找到了匹配项:
breakflag = 0
for i = words
if ((i{1}(1) == user_letter_input) && (length(i{1}) == user_num_input))
breakflag = 1;
break;
end
end
if (breakflag == 0)
disp('There are no matching words');
else
disp(['Your new word is: ' i]);
end