how to write a code on matlab for a function that runs until she gets a regional answer
1 次查看(过去 30 天)
显示 更早的评论
hi everyone!
i have a code i need to write-
i need to write a function that gets from the user amount of money he has and ask him how much money he wants to bet on.
the function needs to check that the value is regional and make sense and afterwards, if the value is good it will stop running, is isnt it will keep running until the user will insert regional value.
so far i wrote this- and its working but i dont know how to make the function keep running till the value is good
could use your help it will be helpful
thanx
function betamount = bet(money)
betamount= input('on what amount do you want to bet on?: ');
if ~isnumeric(betamount)|| betamount<=0 || betamount>money
disp('the betamount is invaild, try again');
end
end
3 个评论
Steven Lord
2024-7-26
Why don't you show us how you've tried to write that using the while keyword. Seeing what you tried will help us tailor our suggestions for how to correct your code. It may be that you've almost got it right and we just need to explain one little detail that will make the code work and improve your understanding of how while (and/or MATLAB in general) works for the future.
回答(1 个)
Milan Bansal
2024-7-26
Hi omer
To make the function keep asking for a valid value for "betamount" until a valid value for "betamount is entered", you can use a while loop along with continue and break statements.
Here is how you can modify your code:
function betamount = bet(money)
while(1)
betamount= input('on what amount do you want to bet on?: ');
if ~isnumeric(betamount)|| betamount<=0 || betamount>money
disp('the betamount is invaild, try again');
else
break;
end
end
end
Please refer to the documention link to learn more:
- while : https://www.mathworks.com/help/matlab/ref/while.html
- break: https://www.mathworks.com/help/matlab/ref/break.html
- continue: https://www.mathworks.com/help/matlab/ref/continue.html
Hope this helps!
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Install Products 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!