概述
这个下午为了改这段代码改了一下午。纠结的点是:
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
%%% 可以写成function,用于循环中直接引用function,下面的部分也可以直接跑function,是否有其他方式?
you.gender = input ("nn please enter your gender. (f/m/x)nn","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("nn Error! Invalid input!nnPlease enter ""f"" for female, ""m"" for male, ""x"" for third sex.rn"); % error report
you.gender = input ("nn please enter your gender. (f/m/x)nn","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
最后
以上就是满意唇膏为你收集整理的matlab表格循环赋值,[初学笔记] matlab中的while loop中使用break语句的新理解和运用: 计算和赋值放到循环里头...的全部内容,希望文章能够帮你解决matlab表格循环赋值,[初学笔记] matlab中的while loop中使用break语句的新理解和运用: 计算和赋值放到循环里头...所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复