I need help with this I don't even think it is right as I have a hard time understanding loops. I was asked to create a Javascript Program that asks for any amount and outputs the number of ice candies that can be bought, and the change if any. My problem is that I do not know if "while" is the correct thing to put or "do" or if I'm missing something Thank you in advance. Here is my code
function minitask() {
var m = document.getElementById("money").value;
var c = 8.5;
m = m - c;
c = c + 1;
while (m <= c)
alert("You can buy " + c + " Icecandy and your change is " + m);
}
<input type="text" id="money" name= "Enter any amount">
<button onclick="minitask()">Calculate</button>
There are some issues in your code both from a algorithmic point of view and a software design point of view.
There is no need to use a loop here, you can do a simple division which will give you the number of candies you can buy:
available money / price for one candy = number of candies to buy
You need to floor()
the result as you cannot buy e.g. 1.2
candys.
The change can then be calculated by
change = available money - number of candies to buy * price of one candy
const
instead of var
to declare variables.type=number
for the <input>
. There are also more option like setting min
and max
which would make sense in your case as e.g. there is no negative money. See MDN docs.<input>
use the placeholder
attribute, not name
.valueAsNumber
on an <input>
element which will retrieve a number right away instead of a string
. Together with input type number
this will make sure you always get a number returned.function minitask() {
const moneyAvailable = document.getElementById("money").valueAsNumber;
if(moneyAvailable < 0) {
alert(`You cannot buy anything with negative money!`)
return;
}
const priceForIceCandy = 8.5;
const noIceCandies = Math.floor(moneyAvailable / priceForIceCandy);
const change = moneyAvailable - noIceCandies * priceForIceCandy;
alert(`You can buy ${noIceCandies} Icecandy and your change is ${change}`);
}
<input type="number" id="money" min="0" placeholder="Enter any amount">
<button onclick="minitask()">Calculate</button>
First you would need to check if the money is enough to buy something
If
it is you should divide the amount of money by the cost of an icecandy, it's true that the classic divider /
doesn't give the change but there is an operator that does, which is called modulo
then return all of that informations to the user
Else
if the user doesn't have enough money tell him that he needs more !