问题:一瓶汽水单价2.5元,四个瓶盖或者两个瓶子可以换取一瓶汽水。给定金额得出一共能喝几瓶汽水?
实现:
#cat drink.java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader; public class drink {
public static void main(String[] args){
System.out.println("汽水单价为2.5元,四个瓶盖或者两个空瓶可以换取一瓶汽水。请输入您购买的金额: ");
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
double money = 0.0;
try {
money = Double.valueOf(br.readLine()).doubleValue();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("您购买汽水的金额是: " + money);
double n = money / 2.5;
int num = (int)n;
int gaizi = num;
int kongping = num;
while (gaizi >= 4 || kongping >= 2) {
int i = (gaizi / 4) + (kongping / 2);
num = num + i;
gaizi = gaizi % 4 + i;
kongping = kongping % 2 + i;
}
System.out.println("您一共可以喝到的汽水数量是: " + num + ",剩余盖子数: " + gaizi
+ ",剩余空瓶数: " + kongping);
}
} 效果图略。