版权声明:本文为我的原创文章,未经博主允许不得转载,如需帮助,请联系[email protected] https://blog.csdn.net/LeegooWang/article/details/81228464
用三种方式实现以下命题:
一瓶汽水1块钱,3个瓶盖换一瓶汽水,2个空瓶换一瓶汽水,假如手里有5块钱,能喝多少瓶汽水
java
采用经典Java OOP方式实现,一目了然。
/**已喝掉*/
static int sodaDrinked = 0;
/**汽水*/
static int soda = 5;
/**瓶盖*/
static int cap = 0;
/**空瓶*/
static int emptyBottle = 0;
public static void main(String[] args){
while (true) {
if (soda > 0) {
System.out.println("喝汽水");
drink();
pring();
continue;
}
if (cap >= 3) {
System.out.println("瓶盖换汽水");
capToSoda();
pring();
continue;
}
if (emptyBottle >= 2) {
System.out.println("空瓶换汽水");
emptyBottleToSoda();
pring();
continue;
}
System.out.println("剩余: 瓶盖" + cap);
System.out.println("剩余: 空瓶" + emptyBottle);
System.out.println("喝掉:" + sodaDrinked);
break;
}
}
public static void drink() {
sodaDrinked++;
soda--;
cap++;
emptyBottle++;
}
public static void capToSoda() {
cap = cap - 3;
soda++;
}
public static void emptyBottleToSoda() {
emptyBottle = emptyBottle - 2;
soda++;
}
public static void pring() {
System.out.println("喝掉" + sodaDrinked + " 瓶盖" + cap + " 空瓶" + emptyBottle + " 剩余汽水" + soda);
}
Excel
细心的QA妹子,使用Excel最终获得答案,大写的赞
Python
下面代码“脏乱差”,不建议初学者去尝试读,因为这要有一丢丢的Python语法基础。
# -*- coding: utf-8 -*-
# @Time : 18/7/26 上午11:56
# @Author : Ligang.Wang[[email protected]]
# @File : SodaHandle.py
#
class SodaHandle():
totalSoda = 0
def change(self, soda, time, cap, bottle):
if time == 0:
cap = soda
bottle = soda
self.totalSoda += soda;
else:
cap += soda
bottle += soda
soda = 0
soda += cap // 3
cap =cap % 3
soda += bottle // 2
bottle = bottle % 2
print(" The time", time, "you could exchange soda:", soda, "remainder bottle:", bottle, ",remainder caps:", cap)
time += 1
if (soda > 0):
self.totalSoda += soda
self.change(soda, time, cap, bottle)
else:
print(" Not enough caps and bottles to exchange!")
def game(self):
self.change(5, 0, 0, 0)
print("You can drink ", self.totalSoda, "soda finally!")
soda = SodaHandle()
soda.game()
执行结果图:
java 迭代
/**
*@Author小浣熊
*/
int p=5;
public void getInt(int k,int g){//k 是空瓶,g 指瓶盖,刚开始5块钱可以买5瓶,所以这里传5,5进来
int aaa=k/2+k%2+g/3;//空
int bbb=k/2+g/3+g%3;//盖
p=p+k/2+g/3;
if (aaa<2&&bbb<3){
YUtils.i("12345","可以喝"+p+"瓶汽水");
}else {
getInt(aaa, bbb);
}
}