While loop question, one too many loops happens.

조회 수: 1 (최근 30일)
Dan Po
Dan Po 2016년 10월 11일
답변: Dan Po 2016년 10월 15일
I want the counter to stop counting once the value '1' is entered. If '1' is entered when running this script, the while loop runs once more before ending. I do not want this. Am I using break the wrong way, or is something else happening?
Thanks
counter=0;
y_n=0;
while y_n==0
if y_n==1
break
end
counter=counter+1
y_n= input('enter 1 or 0\n')
end

채택된 답변

Walter Roberson
Walter Roberson 2016년 10월 11일
You just tested that y_n == 0 in the while statement. It cannot have changed value by the very next statement, at which point you test whether y_n==1 . You should move the "if" to after the input() .
Question: What do you want to have happen if the user enters (for example) 2.134473 ? That is not 0 so the while condition will no longer be true, but the if y_n==1 would be false.
  댓글 수: 3
Dan Po
Dan Po 2016년 10월 11일
Input is not mobile supported. Goodnight.
Dan Po
Dan Po 2016년 10월 11일
편집: Dan Po 2016년 10월 11일
The matlab online app works as I want, but I will check if my desktop version runs correctly. I was using a live script and was not getting my wanted output. Thank you for your help.
format compact
clear
clc
counter=0;
y_n=0;
while y_n==0
y_n= input('enter 1 or 0 to continue or end the loop \n');
if y_n==1
break
end
counter=counter+1;
fprintf('this is loop %d\n',counter)
end
fprintf('the final count of loops is %d\n',counter)

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Dan Po
Dan Po 2016년 10월 15일
Could someone refer me to a place that tells how to qualify inputs?

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by