【代码】买汽水

前言

华为公司买汽水考题

问题

  • 1块钱1瓶汽水,2个空瓶换1瓶汽水,3个瓶盖换1瓶汽水。问:20块钱可以喝到几瓶汽水?

源代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
package io.github.feiju12138;

import java.util.Scanner;

public class BuySoda {

// 初始化剩余金额
static int coin = 20;

// 初始化空瓶数量
static int bottle = 0;

// 初始化瓶盖数量
static int top = 0;

// 初始化喝到汽水计数器
static int sum = 0;

public static void get() {
sum++;
bottle++;
top++;
}

public static void main(String[] args) {

System.out.println("请输入剩余金额(默认为20): ");
Scanner sc = new Scanner(System.in);
coin = sc.nextInt();

// 先用剩余金额购买汽水
while(coin > 0) {
coin--;
get();
}

// 再用空瓶或瓶盖兑换汽水
while(bottle >= 2 || top >= 3) {

if(bottle >= 2) {
bottle -= 2;
get();
}

if(top >= 3) {
top -= 3;
get();
}

}

System.out.println("最终喝到汽水数: "+sum);
System.out.println("剩余水瓶数: "+bottle);
System.out.println("剩余瓶盖数: "+top);

}

}

完成