这个下午为了改这段代码改了一下午。纠结的点是:
1 为什么break语句不发挥作用,依然死循环
2 break发挥作用了,但只有一次重新输入机会
3 break一次重新输入后,gender的输出依然是第一个错误结果,没有被overwrite
用到的运算步骤必须放到循环里面,不然break语句无法执行
下面是我自己的代码,留意其中很重要的计算部分
cig2 = isempty(gender); % if it is an empty input
cig1 = strcmp(gender,s1); % compare the input and the right answer
judcig1 = any(cig1); % use any to test is it any "1" in the answer
以及重新赋值部分
gender = gender;
尤其是计算部分,如果在循环里面省略,是无法达到循环的,会一直死循环或者直接break
如果赋值部分不加上去,有可能会导致输出的结果永远都是错的结果
ingender = cell(1,3); % establish a cell
ingender = {'f','m','x'}; % 3 input strings into the cell
s1 = cellstr(ingender); % transfer from cell to string
ingender = {'f','m','x'}; % 3 input strings into the cell
s1 = cellstr(ingender); % transfer from cell to string
%%% 可以写成function,用于循环中直接引用function,下面的部分也可以直接跑function,是否有其他方式?
you.gender = input ('\n\n please enter your gender. (f/m/x)\n\n','s'); % input your gender here
gender = you.gender; % transefer a struct into a string
cig2 = isempty(gender); % if it is an empty input
cig1 = strcmp(gender,s1); % compare the input and the right answer
judcig1 = any(cig1); % use any to test is it any "1" in the answer
you.gender = input ('\n\n please enter your gender. (f/m/x)\n\n','s'); % input your gender here
gender = you.gender; % transefer a struct into a string
cig2 = isempty(gender); % if it is an empty input
cig1 = strcmp(gender,s1); % compare the input and the right answer
judcig1 = any(cig1); % use any to test is it any "1" in the answer
while ((judcig1 == 0) || (cig2 == 1))
fprintf('\n\n Error! Invalid input!\n\nPlease enter ''f'' for female, ''m'' for male, ''x'' for third sex.\r\n'); % error report
you.gender = input ('\n\n please enter your gender. (f/m/x)\n\n','s'); % input again
gender = you.gender; % transefer a struct into a string % it's necessary to be here
cig2 = isempty(gender); % if it is an empty input
cig1 = strcmp(gender,s1); % compare the input and the right answer
judcig1 = any(cig1); % use any to test is it any "1" in the answer
if (judcig1 == 1) % until the any is "1", end this loop
break; % break the while loop
end
gender = gender; % save the right answer
end % end, when it's the correct answer
fprintf('\n\n Error! Invalid input!\n\nPlease enter ''f'' for female, ''m'' for male, ''x'' for third sex.\r\n'); % error report
you.gender = input ('\n\n please enter your gender. (f/m/x)\n\n','s'); % input again
gender = you.gender; % transefer a struct into a string % it's necessary to be here
cig2 = isempty(gender); % if it is an empty input
cig1 = strcmp(gender,s1); % compare the input and the right answer
judcig1 = any(cig1); % use any to test is it any "1" in the answer
if (judcig1 == 1) % until the any is "1", end this loop
break; % break the while loop
end
gender = gender; % save the right answer
end % end, when it's the correct answer