Reputation: 107
I'm trying to make a code where you input a number n
and the code returns you the number in the Fibonacci sequence.
Example:
When inputting n = 1 the code returns 1, and when you input n = 2 the code returns 1, and when you input n = 3 the code returns 2, and so on.
I'm quite a beginner with javascript so I don't know exactly how to do this.
<html>
<body>
<script type="text/javascript">
function fibonacci(){
var a, b, n, result;
a = 0;
b = 1;
for (var i = 0; i <= n; i++)
{
if(n == 1)
{
return 1;
}
if(n == 0)
{
return 0;
}
result = a + b;
a = b;
b = result;
}
document.getElementById("result").value = result;
}
</script>
<form>
<input id="n" type="number" placeholder="N">
<input id="result" type="number" placeholder="Result" readonly="">
<input id="calculate" type="button" value="Calculate" onclick="fibonacci()">
<input type="reset" value="Clear">
</form>
</body>
</html>
Upvotes: 0
Views: 93
Reputation: 1422
<html>
<body>
<script type="text/javascript">
function fibonacci(){
var n = document.getElementById("n").value;
var result;
var a = 0;
var b = 1;
if(n == 0 || n == 1)
{
result = n;
}
else{
for (var i = 2; i <= n; i++)
{
result = a + b;
a = b;
b = result;
}
}
document.getElementById("result").value = result;
}
</script>
<form>
<input id="n" type="number" placeholder="N">
<input id="result" type="number" placeholder="Result" readonly="">
<input id="calculate" type="button" value="Calculate" onclick="fibonacci()">
<input type="reset" value="Clear">
</form>
</body>
</html>
Upvotes: 0
Reputation: 1438
You didn't initialized n, right?
Add this line before for loop.
n = document.getElementById("n").value
Check your browser console for errors, it shows this kind of errors correctly..
Upvotes: 1