How can I end a for-loop when a condition is met?
14 views (last 30 days)
Show older comments
Hey,
I need to write a piece of code that asks the user to input a value for a temperature in degrees Celsius in the command window (number + ‘enter’) and computes the equivalent temperature in degrees Fahrenheit. For that I used the formula tfahr = 9/5 x tcels + 32. The script should keep running until the user presses the keys q + ‘enter’ in the command window.
This is what I have so far. However, the code is stopping after I entered a number but the program is supposed to keep running. Also, how do I implement that the program ends when I enter 'q'?
for value_celcius = input('Enter temperature in Celsius: ');
if isnumeric(value_celcius)
tfahr = 9/5 * value_celcius + 32;
disp(tfahr)
end
disp('End of program. Goodbye!')
end
Thanks for the help!
0 Comments
Answers (2)
Walter Roberson
on 13 Dec 2020
while true
value_str = input('Enter temperature in Celsius: ', 's');
value_celcius = str2double(value_str);
if isnan(value_celcius)
break;
end
tfahr = 9/5 * value_celcius + 32;
disp(tfahr)
end
disp('End of program. Goodbye!')
You input in string mode in case the user enters non-numeric. You convert the string to double. If the user entered something that is not a valid scalar double, then str2double() returns nan.
Cris LaPierre
on 13 Dec 2020
2 Comments
Cris LaPierre
on 13 Dec 2020
value_str = 'a';
while ~strcmpi(value_str,'q')
value_str = input('Enter temperature in Celsius: ', 's');
...
See Also
Categories
Find more on MATLAB Mobile in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!