MATLAB Answers

How do I get execute while else loop?

3 ビュー (過去 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"

Community Treasure Hunt

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

Start Hunting!

Translated by