Reputation: 112
I have this code and it always outputs 9 no mater what number i put in the textbbox. The equation is 0.25x^(2)+9, the ^(2) means squared.
<html>
<head>
<script>
function calc() {
var number = parseInt(document.getElementById('input').value);
var one = parseInt(0.25*number);
var two = parseInt(one*one);
var three = parseInt(two+9) ;
var sum = parseInt(three);
document.getElementById('num').innerHTML = sum;
}
</script>
</head>
<body>
<p>$10 fee and 2 Commands are free!</p>
<input id="input" type="number" name="quantity" min="1" max="1000"></input><div id="num"></div>
<button onclick="calc()">Calculate</button>
</body>
help?
Upvotes: 1
Views: 112
Reputation: 369
I think that when you are casting it to an int everytime you are rounding everything down to 0 and then when you add +9 you alwasy get 9 as the answer so do:
function calc() {
var number = parseInt(document.getElementById('input').value);
var one = 0.25*number;
var two = one*one;
var three = two+9;
var sum = three;
document.getElementById('num').innerHTML = sum;
}
In addtion you have a methmetical mistake
var one = 0.25*number;
var two = one*one;
two will be like saying two = o.25^2 * x^2
and not two = 0.25 * x^2
like you want so change it to:
function calc() {
var number = parseInt(document.getElementById('input').value);
var one = number*number;
var two = 0.25*one;
var three = two+9;
var sum = three;
document.getElementById('num').innerHTML = sum;
}
And there is an even easyer way:
function calc() {
var number = parseInt(document.getElementById('input').value);
var sum = 0.25*(number*number) + 9;
document.getElementById('num').innerHTML = sum;
}
Upvotes: 0
Reputation: 68393
I have this code and it always outputs 9 no mater what number i put in the textbbox
That is because when you do (0.25 * 0.25)
, it becomes 0.625
. and parseInt
on it makes it 0
.
Which means unless your number is less than 4, it will always print 9 since (0+9)
-> 9
(0 after parseInt)
Also, your code is outputting 10
if number is 4
and 13
if number is 8
.
Right formula would be
sum = Math.pow( number * 0.25, 2 ) + 9
Upvotes: 4