【编程】分别从性能优先和维护两个角度完成printChange函数,输入总金额dCash和应付款dCost,打印出应该找零的钱,且尽量给整钱:比如输入总金额5000,应付款33.34元,则打印出”找零1个10元,1个5元,1个1元,一个5毛,一个5分,一个1分”。
import java.math.BigDecimal;
public class Test3 {
public void printchagnge(double sum,double leave){
double[] a={100,50,20,10,5,1,0.5,0.1,0.05,0.01};
int[] b=new int[10];
//避免误差 比如30-33.34,结果就是16.659999999999997,懵逼
BigDecimal sum1=new BigDecimal(Double.toString(sum));
BigDecimal leave1=new BigDecimal(Double.toString(leave));
double t=sum1.subtract(leave1).doubleValue();
for(int i=0;i<10;i++){
int temp=(int) (t/a[i]);
if(temp>=1){
t=t-a[i]*temp;
}
b[i]=temp;
}
for(int i=0;i<10;i++){
switch(i){
case 0: if(b[i]!=0){
System.out.print(b[i]+"个100元,");
}
break;
case 1: if(b[i]!=0){
System.out.print(b[i]+"个50元,");
}
break;
case 2: if(b[i]!=0){
System.out.print(b[i]+"个20元,");
}
break;
case 3: if(b[i]!=0){
System.out.print(b[i]+"个10元,");
}
break;
case 4: if(b[i]!=0){
System.out.print(b[i]+"个5元,");
}
break;
case 5: if(b[i]!=0){
System.out.print(b[i]+"个1元,");
}
break;
case 6: if(b[i]!=0){
System.out.print(b[i]+"个5毛,");
}
break;
case 7: if(b[i]!=0){
System.out.print(b[i]+"个1毛,");
}
break;
case 8: if(b[i]!=0){
System.out.print(b[i]+"个5分,");
}
break;
case 9: if(b[i]!=0){
System.out.print(b[i]+"个1分");
}
break;
}
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Test3 t=new Test3();
t.printchagnge(50, 33.34);
}
}
function getChange(){ var count=prompt('应付金额:(/元)'); var money=prompt('总金额为:(/元)'); var change=(parseFloat(money)-parseFloat(count)).toFixed(1); console.log(change); if(change<100&&change>0){ var shi=Math.floor(change/10); if(change%10>=5){ var wu=1; var yi=parseInt(change%10)-5; }else{ var wu=0; var yi=parseInt(change%10); } if(change%1!=change){ if(change%1>=0.5){ var wujiao=1; var yijiao=parseFloat(change%1)-0.5; }else{ var wujiao=0; var yijiao=parseInt(change%1); } } } console.log('应找:'+shi+'张10元,'+wu+'张5元,'+yi+'张1元,'+wujiao+'个5角,'+yijiao+'个1角'); } getChange();