[初學筆記] 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

發佈了37 篇原創文章 · 獲贊 17 · 訪問量 12萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章