Why is my Function returning 1 when I expected it to return 4? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Why is my Function returning 1 when I expected it to return 4?

function main() { var depth = parseInt(10); var days = 0; for (var i = 0; i < 20; i++) { depth = depth + 7; days = days + 1; if (depth = 32) { break; } else { depth = depth - 2; } } return days; } var abc = main(); console.log(abc);

8th Mar 2021, 8:49 PM
Moshe Schnitzler
Moshe Schnitzler - avatar
7 Answers
+ 3
Change the condition to: if (depth == 32) "=" is the assignment operator while "==" compares two values.
8th Mar 2021, 8:55 PM
Lukáš Vladař
+ 2
Thank you! I keep making this mistake again & again.......
8th Mar 2021, 8:57 PM
Moshe Schnitzler
Moshe Schnitzler - avatar
+ 2
I immediately see two errors: 1. you do not need to add the number of days +1 in the loop. the variable "i" is already a day counter. 2. don't be hard-wired to the number of days 32. this is not a constant. this is a variable that the test automatically enters itself when checking and this is the depth variable
8th Mar 2021, 8:58 PM
Yaroslav Vernigora
Yaroslav Vernigora - avatar
+ 1
Hi! Are you trying to solve the snail in the well problem?
8th Mar 2021, 8:51 PM
Yaroslav Vernigora
Yaroslav Vernigora - avatar
+ 1
Moshe Schnitzler Try this you will got your mistake: function main() { var depth = parseInt(readLine(), 10); //your code goes here var climb = 7; var slip = 2; var day = 0; for(workdone=0;workdone<=depth;) { day = day+1; workdone = workdone+climb; if(workdone>=depth){ break; } workdone = workdone-slip; } console.log(day); } Happy coding 🤘
9th Mar 2021, 9:20 PM
❤️😍Prerana😍❤️
❤️😍Prerana😍❤️ - avatar
0
Yes
8th Mar 2021, 8:55 PM
Moshe Schnitzler
Moshe Schnitzler - avatar
0
ask your questions if you fail again.
8th Mar 2021, 9:06 PM
Yaroslav Vernigora
Yaroslav Vernigora - avatar