啤酒2元一瓶,四个瓶盖可换一瓶啤酒,2个空瓶也可换一瓶啤酒,10元最多可以喝几瓶,要用js实现
啤酒2元一瓶,四个瓶盖可换一瓶啤酒,2个空瓶也可换一瓶啤酒,10元最多可以喝几瓶,要用js实现
感觉就得用递归啊
var fn=function(x,y,z,m){//x是完整瓶,y是空瓶,z是空盖,m是能喝的瓶数
return x==0&&y<2&&z<4?m:fn(parseInt(y/2)+parseInt(z/4),y%2+x,z%4+x,m+=x)
}
var num=fn(10/2,0,0,0)
<!DOCTYPE html>
<html>
<head>
<title>测试</title>
<meta charset="utf-8">
</head>
<body>
<button id="testBtn">test</button>
<div style="width:300px;">
<p>啤酒2元一瓶,四个瓶盖可换一瓶啤酒,2个空瓶也可换一瓶啤酒,10元最多可以喝几瓶,要用js实现.下面输入所花费用</p>
<input type="text" name="fee" id="allfee">
<button id="openP">计算</button>
</div>
<script type="text/javascript">
window.onload = function() {
var allFee; //总费用
var count = 0; //当前已喝啤酒的数量
var pingzi = 0; //当前的瓶子数
var gaizi = 0; //当前的盖子数量
var calculateCount = document.getElementById("openP");
//点击开始计算
calculateCount.onclick = function(){
allFee = parseInt(document.getElementById('allfee').value)
step1(allFee);
}
//步骤1. 计算用当前费用,所能喝到的啤酒数量
function step1(fee){
let curpi1 = parseInt(fee/2);
count += curpi1;
pingzi += curpi1;
gaizi += curpi1;
step2();
}
//步骤2. 计算用瓶盖兑换啤酒喝的数量
function step2(){
if(gaizi/4 < 1 && pingzi/2 < 1){
alert(count);
return false;
}else{
let curpi2 = parseInt(gaizi/4);
count += curpi2;
pingzi += curpi2;
gaizi = gaizi%4 + curpi2;
step3();
}
}
//步骤3. 计算用空瓶子兑换啤酒喝的数量
function step3(){
if(gaizi/4 < 1 && pingzi/2 < 1){
alert(count);
return false;
}else{
let curpi3 = parseInt(pingzi/2);
count += curpi3;
gaizi += curpi3;
pingzi = pingzi%2 + curpi3;
step2();
}
}
}
</script>
</body>
</html>
function howMany(price, buttle, cap){/*兑换所需单价 瓶子 瓶盖*/
return function get(money, sum = 0, b = 0, pg = 0){
var n = money ? (money / price) << 1 >> 1 : ((b / buttle) << 1 >> 1) + ((pg / cap) << 1 >> 1);
return !n ? sum : get(0, sum + n, b % buttle + n, pg % cap + n);
}
}
var count = howMany(2, 2, 4);
count(10)
怀念pg作为某种货币的时光
def beer(total, cover, bottle):
if cover < 4 and bottle < 2: return total
if cover >= 4: total, bottle, cover = total+cover/4, bottle+cover/4, cover%4+cover/4
if bottle >= 2: total, cover, bottle = total+bottle/2, cover+bottle/2, bottle%2+bottle/2
return beer(total, cover, bottle)
print beer(10/2, 10/2, 10/2)
8 回答4.7k 阅读✓ 已解决
6 回答3.4k 阅读✓ 已解决
5 回答2.8k 阅读✓ 已解决
5 回答6.3k 阅读✓ 已解决
4 回答2.3k 阅读✓ 已解决
5 回答1.3k 阅读✓ 已解决
4 回答2.8k 阅读✓ 已解决
输入金钱10,输出15,所有10元最多应该可以喝15瓶