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

조회 수: 10 (최근 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