Fibonacci in JS with arrays

Asked

Viewed 663 times

2

Hello, I’m trying to make a code in JS that shows the value of Fibonacci in the chosen position using vectors but I don’t know why I’m not getting, does anyone help me in what I’m missing? (The exercise that the teacher went through is about vectors, I know you have how to do without, but I need to do with to train).

function calcularFibonacci() {
    var i = 2;
    var n = parseInt(document.getElementById("numFibonacci").value, 10);
    var fib = new Array();
    fib[0] = 0;
    fib[1] = 1;
    if(fib < 1)
        alert("Valores menores que 1 não são permitidos.");
    else{
        for(i = 2; i <= n; i++){
            fib[i] = fib[i - 2] + fib[i - 1];
        }
        alert("Posição = " + i + ".\nValor = " + n[i]);
    }
}
legend{
	font-weight: bold;
}
input{
	text-align: center;
}
div#site{
	margin-top: 20px;
}
div#fibonacci{
	width: 50%;
	float: left;
}
div#vetor{
	width: 50%;
	float: right;
}
input#numFibonacci{
	width: 60px;
	margin-bottom: 5px;
}
input[name="inputVetor"]{
	width: 45px;
	margin-left: 5px;
	margin-right: 5px;
}
button{
	background-color: #999;;
	margin-top: 5px;
	border: #666;
	color: white;
	padding: 5px 11px;
	text-align: center;
	text-decoration: none;
	display: inline-block;
	font-size: 18px;
	-webkit-transition-duration: 0.7s; /* Safari */
    transition-duration: 0.7s;
}
button[name="exibir"]{
	margin-top: 5px;
}
button:hover{
	background-color: #777; 
}
<!DOCTYPE html>
<html>
<head>
	<title>Exercicio com Arrays</title>
	<meta charset="utf-8">
	<script type="text/javascript" src="vetores.js"></script>
	<script type="text/javascript" src="fibonacci.js"></script>
	<link rel="stylesheet" type="text/css" href="style.css">
	<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" integrity="sha384-WskhaSGFgHYWDcbwN70/dfYBj47jz9qbsMId/iRN3ewGhXQFZCSftd1LZCfmhktB" crossorigin="anonymous">
</head>
<body>
	<div class="container-fluid text-center">
		<div id="site">
			<div id="fibonacci">
				<fieldset>
					<legend>Sequência de Fibonacci</legend>
					Limite Fibonacci: <input type="number" id="numFibonacci" min="1" value="1"><br>
					<button id="buttonFibonacci" onClick="calcularFibonacci()">Exibir elemento na posição</button>
				</fieldset>
			</div>
			<div id="vetor">
				<fieldset>
					<legend>Vetor</legend>
					<input type="number" name="inputVetor" id="input0" value="0">
					<input type="number" name="inputVetor" id="input1" value="0">
					<input type="number" name="inputVetor" id="input2" value="0">
					<input type="number" name="inputVetor" id="input3" value="0">
					<input type="number" name="inputVetor" id="input4" value="0">
					<input type="number" name="inputVetor" id="input5" value="0">
					<input type="number" name="inputVetor" id="input6" value="0">
					<input type="number" name="inputVetor" id="input7" value="0">
					<input type="number" name="inputVetor" id="input8" value="0">
					<input type="number" name="inputVetor" id="input9" value="0">
				</fieldset>
				<button name="exibir" onClick="calcularMaior()">Exibir MAIOR elemento</button>
				<button name="exibir" onClick="calcularMenor()">Exibir MENOR elemento</button><br>
				Último maior valor: <span id="lastMax"></span><br>
				Último menor valor: <span id="lastMin"></span><br>
			</div>
		</div>
	</div>
</body>
</html>

  • 2

    Why not put the code here instead of Jsfiddle?

  • the important part of the JS I posted here, the rest is only if someone wants to see even to help understand, would be a lot on the screen here

  • 1

    If you increment 1 in the value of n and when printing the value of fib[i - 1] works. =)

  • thanks francisco, worked here =)

  • You saw how easy it got?!

1 answer

1

The calculation of the numbers is correct but the way you’re presenting them is that:

alert("Posição = " + i + ".\nValor = " + n[i]);

Is showing the i as position, that when the for is already one element ahead of the n and therefore no longer has the value you want. In addition you are accessing n as if it were an array, when its array is called fib.

Correct would be:

alert("Posição = " + n + ".\nValor = " + fib[n]);
//                   ^--                   ^---

See this change in action:

function calcularFibonacci() {
    var i = 2;
    var n = parseInt(document.getElementById("numFibonacci").value, 10);
    var fib = new Array();
    fib[0] = 0;
    fib[1] = 1;
    if(fib < 1)
        alert("Valores menores que 1 não são permitidos.");
    else{
        for(i = 2; i <= n; i++){
            fib[i] = fib[i - 2] + fib[i - 1];
        }
        alert("Posição = " + n + ".\nValor = " + fib[n]);
    }
}
legend{
	font-weight: bold;
}
input{
	text-align: center;
}
div#site{
	margin-top: 20px;
}
div#fibonacci{
	width: 50%;
	float: left;
}
div#vetor{
	width: 50%;
	float: right;
}
input#numFibonacci{
	width: 60px;
	margin-bottom: 5px;
}
input[name="inputVetor"]{
	width: 45px;
	margin-left: 5px;
	margin-right: 5px;
}
button{
	background-color: #999;;
	margin-top: 5px;
	border: #666;
	color: white;
	padding: 5px 11px;
	text-align: center;
	text-decoration: none;
	display: inline-block;
	font-size: 18px;
	-webkit-transition-duration: 0.7s; /* Safari */
    transition-duration: 0.7s;
}
button[name="exibir"]{
	margin-top: 5px;
}
button:hover{
	background-color: #777; 
}
<!DOCTYPE html>
<html>
<head>
	<title>Exercicio com Arrays</title>
	<meta charset="utf-8">
	<script type="text/javascript" src="vetores.js"></script>
	<script type="text/javascript" src="fibonacci.js"></script>
	<link rel="stylesheet" type="text/css" href="style.css">
	<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" integrity="sha384-WskhaSGFgHYWDcbwN70/dfYBj47jz9qbsMId/iRN3ewGhXQFZCSftd1LZCfmhktB" crossorigin="anonymous">
</head>
<body>
	<div class="container-fluid text-center">
		<div id="site">
			<div id="fibonacci">
				<fieldset>
					<legend>Sequência de Fibonacci</legend>
					Limite Fibonacci: <input type="number" id="numFibonacci" min="1" value="1"><br>
					<button id="buttonFibonacci" onClick="calcularFibonacci()">Exibir elemento na posição</button>
				</fieldset>
			</div>
			<div id="vetor">
				<fieldset>
					<legend>Vetor</legend>
					<input type="number" name="inputVetor" id="input0" value="0">
					<input type="number" name="inputVetor" id="input1" value="0">
					<input type="number" name="inputVetor" id="input2" value="0">
					<input type="number" name="inputVetor" id="input3" value="0">
					<input type="number" name="inputVetor" id="input4" value="0">
					<input type="number" name="inputVetor" id="input5" value="0">
					<input type="number" name="inputVetor" id="input6" value="0">
					<input type="number" name="inputVetor" id="input7" value="0">
					<input type="number" name="inputVetor" id="input8" value="0">
					<input type="number" name="inputVetor" id="input9" value="0">
				</fieldset>
				<button name="exibir" onClick="calcularMaior()">Exibir MAIOR elemento</button>
				<button name="exibir" onClick="calcularMenor()">Exibir MENOR elemento</button><br>
				Último maior valor: <span id="lastMax"></span><br>
				Último menor valor: <span id="lastMin"></span><br>
			</div>
		</div>
	</div>
</body>
</html>

I take this opportunity to remind you that the parseInt will normally interpret on the basis of 10 unless the string input is formatted as hexadecimal (0x...) or as octal (number with zeros on the left). For this reason it is very common to use the parseInt without indicating the basis (Radix).

  • thanks for the help, this parseint I did not know, but I think I will continue indicating the basis for the route of doubts ^^

Browser other questions tagged

You are not signed in. Login or sign up in order to post.