Search code examples
javascriptpromptcalculation

Divide numbers from prompt in new function


I have a program written that calculates bank notes that you have to pay (2,5,10,20,...) from a number you type into the prompt.

I would like to take it further to the next step - I want to take that number from the prompt that was inserted on the first step and divide it by number user types into a new prompt to calculate the average cost of one item.

How can I do that?

This is the code that I have written for the first part.

var stevilo = prompt("Vnesi znesek:");

var bankovec = [500, 200, 100, 50, 20, 10, 5, 2, 1];
var stevilo_bankovcev = 0;
var izpisi = "";
for (i = 0; i < bankovec.length; i++) {
  var y = stevilo / bankovec[i];
  if (y >= 1) {
    var razlika = Math.floor(y) * bankovec[i];
    stevilo = stevilo - razlika;
    stevilo_bankovcev = Math.floor(y) + stevilo_bankovcev;
    izpisi = izpisi + Math.floor(y) + "x" + bankovec[i] + ",";
    console.log(izpisi);
  }
}
window.onload = function() {
  document.getElementById("gremo").innerHTML = "Za plačilo je potrebno " + izpisi;
}
<span id="gremo"></span>


Solution

  • I am not sure whether I understand the question correctly, but if the only thing you wanted to add to your program was another variable which user inputs, and then do a division with that variable, this would do the trick (although Im not entirely sure what the usage of this would be):

    var stevilo = prompt("Vnesi znesek:");
    var division = prompt("Dividing by this number:");
    
    var bankovec = [500, 200, 100, 50, 20, 10, 5, 2, 1];
    var stevilo_bankovcev = 0;
    var total = stevilo/division;
    var izpisi = "";
    for (i = 0; i < bankovec.length; i++) {
      var y = stevilo / bankovec[i];
      if (y >= 1) {
        var razlika = Math.floor(y) * bankovec[i];
        stevilo = stevilo - razlika;
        stevilo_bankovcev = Math.floor(y) + stevilo_bankovcev;
        izpisi = izpisi + Math.floor(y) + "x" + bankovec[i] + ",";
        console.log(izpisi);
      }
    }
    window.onload = function() {
      document.getElementById("gremo").innerHTML = "Za plačilo je potrebno " + izpisi + " whereas the division's result is: " + total;
    }
    <span id="gremo"></span>

    Basically just call another prompt, save it into another variable and then divide with it.

    Regards, B