public static void main(String[] args) {
// 所有金额以分为单位
int money = 146
// 所有钞票面以分为单位,从大到小排列,10000是100块,20是2角
int[] rmbs = { 10000, 5000, 2000, 1000, 500, 100, 50, 20, 10, 5, 2, 1 }
// rest是剩余的钱,刚开始为所求的钱,随便选钱rest越变越小,直到为0
int rest = money
for (int rmb : rmbs) {
// num为钞票个数
int num = rest / rmb
if (num >0) {
rest = rest - rmb * num
System.out.println("钞票面额(分):" + rmb + " 个数:" + num + " 还差多少钱(分):" + rest)
// 钱凑齐了,程序结束
if (rest == 0) {
System.exit(1)
}
} // end if num
} // end for rmb
}
}
for(i=0i<20){for(j=0j<(100-5*i)/2){
for(k=0k<100-5*i-2*j){
flag++}}}
按大的在外面,小的在里面比较好,这样里面的循环不会变成负的
另外我写错了个,应该是5*i-2*j
还有,flag要给初值的,你不给的话也应该会报错的吧
import java.io.IOExceptionimport java.io.InputStream
import java.util.ArrayList
import java.util.List
public class Change {
/**
* @param args
*/
public static void main(String[] args) {
System.out.println("请输入价格:")
double m = Double.parseDouble(getInputLine())
System.out.println("请付款金额:")
double c = Double.parseDouble(getInputLine())
change(m, c)
}
public static String getInputLine() {
InputStream inputStream = System.in
List<Byte> cmdBuffer = new ArrayList<Byte>()
int t
try {
while (true) {
t = inputStream.read()
if (t == '\n') {
byte[] bs = new byte[cmdBuffer.size()]
for (int i = 0 i < cmdBuffer.size() i++) {
bs[i] = cmdBuffer.get(i)
}
return new String(bs).trim()
} else {
cmdBuffer.add((byte) t)
if (cmdBuffer.size() > 1024) {
return null
}
}
}
} catch (IOException e) {
return null
}
}
public static double[] moneys = { 0.01, 0.02, 0.05, 0.1, 0.2, 0.5, 1, 2, 5, 10, 20, 50, 100 }
/**
* @param m
* 价格
* @param c
* 付款
*/
public static void change(double m, double c) {
double z = c - m
if (z < 0) {
System.out.println("付款不足!")
} else if (z == 0) {
System.out.println("不需要找零。")
} else {
System.out.println("找零共:" + z + "元")
System.out.println("其中:")
for (int i = moneys.length - 1 i >= 0 i--) {
double money = moneys[i]
int count = 0
while ((z - money) >= 0) {
z -= money
count++
}
if (count > 0) {
System.out.println(money + "元:" + count + "张")
}
}
}
}
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)