How do you get a function to return true or false to the script where the function was called?

15 次查看(过去 30 天)
I have 2 scripts for a simple game of blackjack. The first script called 'blackjack.m' gives the user initial options like learn the rules and place wages, while the second script 'play_blackjack' deals the players and dealers hands and uses several if loops to determine who wins. On each of these if loops Ive added a game=true/false depending on who the winner is. Back in the first script, when I write 'if game==true' or 'game==false', it doesnt recognise that I have determined these variables in the play_blackjack function and gives the error message. Ive tried initialising the variable 'game' and that didnt do anything. Ive also tried using 1 and 0 instead of true/false and still no changes. Note in the first script I have written simple disp commands 'WIN' and 'LOSE'. These are just temporary so I can finally see if its working or not. Ive been trying to figure this out for a while.

回答(1 个)

chicken vector
chicken vector 2023-4-26
编辑:chicken vector 2023-4-26
the file play_blackjack.m is not a script, but a function.
In blackjack.m change the line:
play_blackjack
To:
game = play_blackjack;
Side tip.
Instead of doing
if game == true
fprintf("WIN")
end
if game == false
fprintf("LOSE")
end
Do:
if game
fprintf("WIN")
else
fprintf("LOSE")
end
Or:
if game
fprintf("WIN")
end
if ~game
fprintf("LOSE")
end
  2 个评论
Steven Lord
Steven Lord 2023-4-26
I'd also consider giving that variable a more descriptive name. The name "game" doesn't scream to me that it's a logical variable indicating whether or not the player won. Perhaps use a name like "playerWon", in which case the code is fairly self-explanatory even for people who may not be familiar with MATLAB code.
if playerWon
fprintf("YOU WIN")
else
fprintf("YOU LOSE")
end
If I showed that to my mother (who is most definitely not a programmer) and told her "fprintf prints a message to the screen" she likely could understand and explain that code segment.
Callum
Callum 2023-4-26
Thank you so much! Literally saved me from an F! Thanks for your advice on the variable name and the side tip. Ive still got a bunch of formatting to do but thats a good start.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Strategy & Logic 的更多信息

产品


版本

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by