...

View Full Version : Javascript maths problem



Ruriko
06-03-2009, 11:40 AM
I'm having trouble with my script. The script is suppose to calculate how many computers & netbooks it can fit on a bench. A computer can fit 4 per bench (ratio 4:1) and a netbook can fit 5 per bench (5:1). The problem is if I enter 3 computers & 2 netbooks it would give me 2 benches instead of 1. I think I did my maths wrong



<script type="text/javascript">
do {
computer = window.prompt("How many desktop computers do you require?", "0");
computer_num = parseInt(computer);

if (isNaN(computer_num)) /* If the user enters an invalid number it will prompt you to put a valid number */
{
window.alert("Enter a number 0 or above")
}

}

while(isNaN(computer_num));

computer_total = computer/4

do {
netbook = window.prompt("How many netbooks do you require?", "0");
netbook_num = parseInt(netbook);

if (isNaN(netbook_num))
{
window.alert("Enter a number 0 or above")
}

}

while(isNaN(netbook_num));

netbook_total = netbook/5

benches = Math.ceil(computer_total) + Math.ceil(netbook_total);
document.writeln ("<p>" + benches + " benches</p>");
</script>

venegal
06-03-2009, 11:56 AM
No, you did your thoughts wrong. Just try it with real computers and benches.

randomuser773
06-03-2009, 11:58 AM
benches = Math.ceil(computer_total) + Math.ceil(netbook_total);

You need the ceiling of the addition, not the sum of the ceilings:

benches = Math.ceil(computer_total + netbook_total);

Ruriko
06-03-2009, 12:01 PM
benches = Math.ceil(computer_total + netbook_total);
still gives me the answer of 2 benches if I input 3 computers & 2 netbooks

randomuser773
06-03-2009, 01:20 PM
benches = Math.ceil(computer_total + netbook_total);
still gives me the answer of 2 benches if I input 3 computers & 2 netbooks

3 computers = 0.75
2 netbooks = 0.4



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum