How do I get execute while else loop?

조회 수: 21 (최근 30일)
Steven Tan
Steven Tan 2021년 6월 17일
편집: Jan 2021년 6월 18일
Hello. I am trying to create a loop that when userinput == 'yes' for the question to continue, it will run the questions. But if the userinput == 'no', I want it to print 'Thank you'.
I am having trouble to get the code to execute the part when userinput == 'no'.
answer = 'yes';
if answer == 'yes'
while (answer == 'yes')
dia = input('Enter the circle diameter : ');
choice = input('Enter your choice : ');
if choice == 1
area = pi * (dia/2)^2;
fprintf('Area of circle = %.1f \n', area);
elseif choice == 2
circum = pi * dia;
fprintf('Circumference of circle = %.1f \n', circum);
else
fprintf('Invalid choice \n');
end
answer = input('Do you want to continue? [yes/no] : ', 's');
end
else
fprintf('Thank you');
end

답변 (1개)

Jan
Jan 2021년 6월 17일
편집: Jan 2021년 6월 18일
The == operator compares its arguments elementwise. This works only if one of the array is a scalar or if bother have the same size.
Use strcmp to compare CHAR vectors. The == operator works with strings:
answer = 'yes';
if strcmp(answer, 'yes')
while strcmp(answer, 'yes')
Or
answer = "yes"; % Double quotes!
if answer == "yes"
while answer == "yes"

카테고리

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