'Fibonacci with two functions
I amb trying to create a Fibonacci sequence with two functions. Can you tell me where am I wrong, please?
Thank you!
function aurea(quantitatNum){
let numFibo = [];
numFibo[0] = 0, numFibo[1] = 1;
for (i = 2; i < quantitatNum; i++) {
numFibo[i] = numFibo[i - 2] + numFibo[i - 1];
numFibo.push(i);
numFibo.pop(quantitatNum);
}
return aureaNum;
}
function calcular(){
let quantitatNum = Number(document.getElementById("quantitatNum").value);
let dadaCorrecta = Number.isInteger(quantitatNum) && quantitatNum > 0 ? true : false;
let resposta = document.getElementById("resposta");
let aureaNum;
if (dadaCorrecta){
aureaNum = aurea(quantitatNum);
resposta.innerHTML = aureaNum;
} else {
resposta.innerHTML = "Error! Introdueix un valor enter positiu!";
}
}
Well, at the begining I created the following structure and it works. But when I tryied insert another function it didn't work...
function calcular(){
let quantitatNum = Number(document.getElementById("quantitatNum").value);
let dadaCorrecta = Number.isInteger(quantitatNum) && quantitatNum > 0 ? true : false;
let resposta = document.getElementById("resposta");
let numFibo = [];
numFibo[0] = 0, numFibo[1] = 1;
if (dadaCorrecta){
for (i = 2; i < quantitatNum; i++) {
numFibo[i] = numFibo[i - 2] + numFibo[i - 1];
numFibo.push(i);
numFibo.pop(quantitatNum);
}
resposta.innerHTML = numFibo;
} else {
resposta.innerHTML = "Error! Introdueix un valor enter positiu!";
}
}
Solution 1:[1]
Some issues:
return aureNummakes no sense: that is not a variable that is declared inaurea, nor has it participated in the calculation.numFibo.push(i): why would you push the index in this array? The previous line already adds the ith value to the array.popdoes not take an argument. No idea what you try to do here. However, after the loop, you could usepopto extract the last summed value and return it.- Depending on how you number Fibonacci numbers, the loop should continue until
<=.
Here is a corrected version:
function aurea(quantitatNum){
let numFibo = [];
numFibo[0] = 0, numFibo[1] = 1;
for (i = 2; i <= quantitatNum; i++) {
numFibo[i] = numFibo[i - 2] + numFibo[i - 1];
}
return numFibo.pop();
}
function calcular(){
let quantitatNum = Number(document.getElementById("quantitatNum").value);
let dadaCorrecta = Number.isInteger(quantitatNum) && quantitatNum > 0 ? true : false;
let resposta = document.getElementById("resposta");
let aureaNum;
if (dadaCorrecta){
aureaNum = aurea(quantitatNum);
resposta.innerHTML = aureaNum;
} else {
resposta.innerHTML = "Error! Introdueix un valor enter positiu!";
}
}
<input id="quantitatNum"><button onclick="calcular()">Do</button>
<div id="resposta"></div>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | trincot |
