If you want to quit entire program, type quit again in command window
About While Loops problems
조회 수: 3 (최근 30일)
이전 댓글 표시
Is there anyway to end the program by entering "quit"? As the program keeps going despite displays "Exiting..."
The following is the syntax.
function Individual_Project_Final()
disp('Welcome to Unit Converter interface! ');
disp(' ');
while true
% Accept user input
input_str = input('Enter a number to be converted (or type "quit" to exit program): ', 's');
% Check if the user wants to quit
if strcmp(input_str, 'quit')
disp('Exiting...')
break;
end
% Convert input string to a number
numin = str2double(input_str);
% Check if the input is a valid number
if isnan(numin)
disp('Input invalid. Please enter a whole or decimal number (or type "quit to exit program): ');
else
disp('Input valid. Now please select the unit conversion type (or type "quit to exit program): ');
break;
end
end
% Display the menu for selecting conversion type
disp(' ')
disp('Select conversion type:')
disp('1) Celsius to Fahrenheit')
disp('2) Fahrenheit to Celsius')
disp('3) Centimeters to Inches')
disp('4) Inches to Centimeters')
disp('5) Meters to Foot')
disp('6) Foot to Meters')
disp('7) Kilometers to Miles')
disp('8) Miles to Kilometers')
disp('9) Grams to Ounces')
disp('10) Ounces to Grams')
disp('11) Kilograms to Pounds')
disp('12) Pounds to Kilograms')
disp('13) Tonnes to Tons')
disp('14) Tons to Tonnes')
while true
% Accept user input
input_str = input('Please select conversion type (1-14) (or type "quit" to exit): ', 's');
% Check if the user wants to quit
if strcmp(input_str, 'quit')
disp('Exiting...');
break;
end
% Convert input string to a number
convtype = str2double(input_str);
% Check if input is a valid conversion type
if ~ismember(convtype, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14])
disp('Conversion type invalid. Please enter a number from 1 to 14 (or type "quit to exit program): ');
else
disp('Input valid. We are now finalizing the resluts based on your input. ');
break;
end
end
% Call the user-defined function from Module 2
[numout,unit] = MyUnitConverter(numin,convtype);
% Output generation
disp(' ');
fprintf('The converted number is: %.2f %s\n', numout, unit);
end
댓글 수: 3
답변 (1개)
VBBV
2024년 5월 19일
It has already exited, the first while loop, but it's waiting for next input from user ... See the message at bottom left of window in workspace, you need to select or provide a number
댓글 수: 9
VBBV
2024년 5월 20일
Try using the code which i modified (that has only one while loop , inner while loop is commented )
참고 항목
카테고리
Help Center 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!