I have an array including numbers,( array order is fixed), i would like to see how many of item i can take from this array with my ordersize in JS My code gives wrong results, For example 500 unit can buy first 2 items and 0,66 of 3rd item so total 2,66 can be taken but code gives 4, for 250 unit i can take 1st item full and 0,75 of second item total 1,75 i can take but code gives 1.5.
For 300 gives 2 this is true but generally gives wrong result. I ve changed the line of result inside or out side of for and if conditions , it affects result but again wrong results come. (for given array 2100 unit ordersize will take all items with 6 result )
function calculateOrder() {
var coinArray = [100, 200, 300, 400, 500, 600];
var orderSize = 500;
var sum = 0;
var i = 0;
for (i = 0; i < coinArray.length - 1; i++) {
if (sum < orderSize) {
sum += coinArray[i];
}
return i + (orderSize - sum) / coinArray[i];
}
}
document.write(calculateOrder());
Aucun commentaire:
Enregistrer un commentaire