Effacer les filtres
Effacer les filtres

Getting an if statement to accept a word.

5 vues (au cours des 30 derniers jours)
Travis
Travis le 28 Mar 2013
I'm writing a program to find a persons training heart rate based on a few factors and when it asks for fitness level I want the user to be able to use low, medium or high as and answer.
disp('Enter your information to find your ideal training heart rate.')
age= input('Enter your age:');
rhr= input('What is your resting heart rate:');
fit= input('Would you describe your fitness level as low, medium or high?');
if fit=='low'
fit=0.55;
elseif fit=='medium'
fit=0.65;
else fit=='high'
fit=0.8;
end
thr=[(220-age)-rhr]*fit+rhr;
disp('Your ideal training heart rate is', num2str(thr))
I can get it to accept 'low' but not just low. How can I get it to accept words?
also what am i missing from my final part in order to get is to display everything?
  1 commentaire
Mahdi
Mahdi le 28 Mar 2013
Can you be more specific with display everything? Your code displays the thr value to me, is that what you want? Look at my answer for more information.

Connectez-vous pour commenter.

Réponses (2)

Azzi Abdelmalek
Azzi Abdelmalek le 28 Mar 2013
disp('Enter your information to find your ideal training heart rate.')
age= input('Enter your age:');
rhr= input('What is your resting heart rate:');
fit= input('Would you describe your fitness level as low, medium or high?');
id=listdlg('PromptString','make your choice',...
'SelectionMode','single',...
'ListString',{'low','medium','high'})
if id==1
fit=0.55;
elseif id==2
fit=0.65;
else
fit=0.8;
end
thr=[(220-age)-rhr]*fit+rhr;
disp('Your ideal training heart rate is', num2str(thr))

Mahdi
Mahdi le 28 Mar 2013
Modifié(e) : Mahdi le 28 Mar 2013
Just change your inputs function to be:
fit=input('Would you describe your fitness level as low, medium, or high?', 's')
The 's' at the end tells MATLAB it's a string, so now you can input low as an answer.
You should use the strcmp() function when comparing strings.
So, in your case, using the first example,
if strcmp(fit, 'low')==1
...
end
You might want to look at strncmp as well. You still need to put the quotations though.
Make sure to use elseif fit=='high' as well in that line. (or just else on its own)

Catégories

En savoir plus sur Manage System Data dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by