-2
的預期回報率如下所示:帶浮動Javascript數組的內部點值意外的結果
checkCashRegister(3.26,100.00,[[ 「便士」,1.01],[ 「鎳」,2.05],[「DIME 「,3.10」,[「QUARTER」,4.25],[「ONE」,90.00],[「FIVE」,55.00],[「TEN」,20.00],[「TWENTY」,60.00] ,[100.00]])應返回 [[「TWENTY」,60.00],[「TEN」,20.00],[「FIVE」,15.00],[「ONE」,1.00],[「QUARTER」,0.50] [「DIME」,0.20],[「PENNY」,0.04]]。
當我看着控制檯中的輸出,它看起來與預期輸出一樣,但我不知道它失敗的原因。我會感謝你的幫助。這裏是鏈接到我的代碼:https://jsfiddle.net/do91m6qy/
function checkCashRegister(price, cash, cid) {
var change;
// Here is your change, ma'am.
change="Insufficient Funds";
change="Closed";
var typeObj={"PENNY":0.01,"NICKEL":0.05,"DIME":0.10,"QUARTER":0.25,"ONE":1,"FIVE":5,"TEN":10,"TWENTY":20,"ONE HUNDRED":100};
var changeArr=[["PENNY", 0],["NICKEL", 0],["DIME", 0],["QUARTER", 0], ["ONE", 0], ["FIVE", 0], ["TEN", 0], ["TWENTY",0], ["ONE HUNDRED", 0]];
var diff=cash-price;
var total=cid.reduce(function(acc,val){
//console.log("acc",acc,"val",val);
return Math.round((acc+val[1])*100)/100;
},0);
//console.log("total",total);
if(diff>total)
\t return "Insufficient Funds";
else if(diff==total)
\t return "Closed";
cid.reverse().forEach(function(arr,i){
\t var key=arr[1];
var curr=typeObj[arr[0]];
var sum=0;
diff=Math.round(diff*100)/100;
console.log("curr",curr,"key",key,"diff",diff,"diff/curr",diff/curr);
//console.log("changeArr[changeArr.length-1-i][1]",changeArr[changeArr.length-1-i][1]);
\t while(key>=curr && (diff/curr>=1)){
diff=Math.round(diff*100)/100;
console.log("inside","curr",curr,"key",key,"diff",diff,"diff/curr",diff/curr); sum+=curr;
changeArr[changeArr.length-1-i][1]=sum/100*100;
key-=curr;
if(diff>=curr)
diff-=curr;
}
});
console.log("changeArr",changeArr);
changeArr=changeArr.filter(function(arr){
return arr[1]!==0;
});
console.log(changeArr);
if(diff===0)
\t return changeArr;
console.log("------");
return "Insufficient Funds";
}
// Example cash-in-drawer array:
// [["PENNY", 1.01],
// ["NICKEL", 2.05],
// ["DIME", 3.10],
// ["QUARTER", 4.25],
// ["ONE", 90.00],
// ["FIVE", 55.00],
// ["TEN", 20.00],
// ["TWENTY", 60.00],
// ["ONE HUNDRED", 100.00]]
checkCashRegister(3.26, 100.00, [["PENNY", 1.01], ["NICKEL", 2.05], ["DIME", 3.10], ["QUARTER", 4.25], ["ONE", 90.00], ["FIVE", 55.00], ["TEN", 20.00], ["TWENTY", 60.00], ["ONE HUNDRED", 100.00]]);
我試圖修復問題的格式,使可讀性,但我根本不能。我不完全確定你的問題是什麼,但如果你得到一個完全不同的數據結構,它不能成爲一個浮點數學問題。 –
「當我查看控制檯中的輸出時,它看起來與預期輸出相同,但我不知道它失敗的原因。」 - 如果輸出與預期的輸出相同......爲什麼你認爲它失敗? – Quentin
@ÁlvaroGonzález對不起,在stackoverflow非常新,問題解決沒有問題 –