Testing a created function

16 Ansichten (letzte 30 Tage)
Alicia Sood
Alicia Sood am 9 Dez. 2019
Kommentiert: Star Strider am 9 Dez. 2019
I am trying to write and test a function to determine whether a person is old enough to drink or not (with the legal age being 19).
For some reason when I test the function the code will run but not display the message that I set. How can I fix this code so that it will display the proper message?
FUNCTION:
function[ans] = drink(age)
if(age<19)
ans = 'no';
else
ans = 'yes';
end
TESTING:
clear
clc
addpath('Library')
age = input('Enter your age: ' );
ans = drink(age);
if(ans == strcmpi(ans, 'yes'))
disp('Old enough to drink')
elseif(ans == strcmpi(ans, 'no'))
disp('Not old enough to drink')
end
  1 Kommentar
Adam
Adam am 9 Dez. 2019
Bearbeitet: Adam am 9 Dez. 2019
Don't call variables 'ans', for starters. Also, this 'logic' is really confusing:
if(ans == strcmpi(ans, 'yes'))
...
end
Just
if( strcmp( result, 'yes' ) )
should work fine. It seems a bit odd though that you put logic in your function to return 'yes' or 'no', then more logic that effectively checks the same thing to the convert to a different string!

Melden Sie sich an, um zu kommentieren.

Akzeptierte Antwort

Star Strider
Star Strider am 9 Dez. 2019
First, it is best not to use ‘ans’ as a variable, since it is the default variable and can be overwritten.
Second, the the if and elseif conditions were not coded correctly.
This works:
if strcmpi(rsp, 'yes')
disp('Old enough to drink')
elseif strcmpi(rsp, 'no')
disp('Not old enough to drink')
end
  2 Kommentare
Alicia Sood
Alicia Sood am 9 Dez. 2019
Noted, thank you!
Star Strider
Star Strider am 9 Dez. 2019
As always, my pleasure!

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Get Started with MATLAB 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