How do I get execute while else loop?

19 Ansichten (letzte 30 Tage)
Steven Tan
Steven Tan am 17 Jun. 2021
Bearbeitet: Jan am 18 Jun. 2021
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

Antworten (1)

Jan
Jan am 17 Jun. 2021
Bearbeitet: Jan am 18 Jun. 2021
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"

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by