using a double or triple for loop?

My professor has given our class an optional problem for fun, and I am really curious as to how to simply code this... The question is: I have $10, and each beer costs $2. The bar is running a deal where for every 2 empty beer bottles returned, you receive a free beer, and for every 4 bottle caps returned you receive a free beer. Write a code to see how many beers you can get for $10. (The free beer received counts towards the bottles and caps needed for more beer) - Any help will be appreciated!

2 个评论

I don't think you need Matlab to do this... think carefully about the problem and try working it through.
How about showing what you have attempted so far in the way of code?

请先登录,再进行评论。

回答(1 个)

Roger Stafford
Roger Stafford 2016-4-26
Jgg is correct that you wouldn't need matlab to do this problem, but if you generalize to have N number of dollars initially instead of ten, then it becomes a little more worthy of matlab coding.
For that general case I would suggest a while-loop and keeping track of four different quantities, namely, 1) the number of dollars you still possess, 2) the number of beers you have obtained so far, 3) the number of empty bottles you currently have on hand, and 4) the number of caps you have. At each trip through the loop, you should adjust these numbers in accordance with whatever transaction is occurring, taking into consideration that none of the numbers is allowed to go negative. The condition for exiting the while-loop should be that you have reached a situation where no further transaction is possible.
Note: You may question whether this constitutes a valid answer and very possibly you would be right. In any case I hope you succeed.

类别

帮助中心File Exchange 中查找有关 MATLAB 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by