I'm trying to make an alert which will tell you the n'th step of Fibonacci using a for loop. What I have so far is
var x=1;
var y=1;
var call = function(n) {
if (n===1||2) {
alert(1);
}
else {
for(i=3; i<n+1; i++) {
y=(x+y);
x=y-x;
if (i===n) {
alert(y);
}
}
}
};
call(prompt("Calculate Fibonacci to how many steps?"));
How I've tried to make it work is:
But I'm always alerted with 1, even if I change the alert from the first if statement from 1 to a string. I'm not sure if there's an error in the code or in the logic of it.
I've seen a for loop isn't the most efficient way to do this, but I'd like to get it to work this way for learning's sake. I'm only a few lessons in Code Academy so my experience is very limited. Other pages that address this or a very similar problem are
Fibonacci calculator steps
http://ecomputernotes.com/js/javascript-tutorial/javascript-for-loop
https://answers.yahoo.com/question/index?qid=20091001160834AA5xiZ1
This
if (n===1||2) {
needs to be
if (n===1||n===2) {
Your code is evaluating the truthiness of 2, which is always true.
Also, it's unnecessary to evaluate i===n
during each iteration. This will be true only after the last iteration of the loop, so just alert(y)
after the loop.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.