[初学笔记] matlab中的while loop中使用break语句的新理解和运用: 计算和赋值放到循环里头

这个下午为了改这段代码改了一下午。纠结的点是:

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 ('\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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值