Help with Functions | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Help with Functions

Can someone tell me why my Fibonacci Sequence code does not work as I have written it. It seems logical to me that it should work https://code.sololearn.com/czjQq6VsK8TW/#cpp

1st Jun 2017, 7:22 PM
Bryan
12 Answers
+ 4
Check out the lessons on loops in the C++ course here...
1st Jun 2017, 7:26 PM
Kuba Siekierzyński
Kuba Siekierzyński - avatar
+ 4
If you want to do it with recursion instead of loops, you have to make this function return something. Hint: If x == 0 or x==1 it should return 1 else it should return itself(x-1)/itself(x-2)
1st Jun 2017, 7:36 PM
Kuba Siekierzyński
Kuba Siekierzyński - avatar
+ 2
#include <iostream> using namespace std; //Fibonacci Sequence int fuxn(unsigned int x){ return (x<2)?x:(fuxn(x-1)+fuxn(x-2)); } int main() { cout<< fuxn(10); return 0; }
1st Jun 2017, 7:50 PM
Julio Cesar Rosales Rodriguez
Julio Cesar Rosales Rodriguez - avatar
+ 1
One is the assignment operator, one is the equality operator. = is the assignment operator. b = 1 will set the variable b equal to the value 1. == is the equality operator. it returns true if the left side is equal to the right side, and returns false if they are not equal With only rare exceptions, you should not be using the assignment operator inside an if clause, but that is an extremely common beginner mistake.
1st Jun 2017, 7:41 PM
Miska Rantala
Miska Rantala - avatar
+ 1
Your original never worked because it didn't make sense. I highly suggest reviewing functions in the course supplied here.
1st Jun 2017, 7:47 PM
Rrestoring faith
Rrestoring faith - avatar
+ 1
thanks I've reviewed functions twice. it makes sense to me this stuff is confusing
1st Jun 2017, 8:12 PM
Bryan
+ 1
(X <2)?×: (fuxn(x-1) + fuxn(x-2)); It is equal to a sentence if if x <2 returns x or sea 1 or 0 otherwise it calls a fuxn (x-1) + fuxn (× -2) or sea something similar to what you did
1st Jun 2017, 9:00 PM
Julio Cesar Rosales Rodriguez
Julio Cesar Rosales Rodriguez - avatar
+ 1
Unsigned int ensures that the function parameter is the set of positive integers including zero
1st Jun 2017, 9:02 PM
Julio Cesar Rosales Rodriguez
Julio Cesar Rosales Rodriguez - avatar
0
Put double == between numbers it's complaining about. That should at least fix the errors!
1st Jun 2017, 7:28 PM
Miska Rantala
Miska Rantala - avatar
0
So I tried == and it didn't work. Also I did the courses on the loops. I don't see why I need a loop here. It should automatically loop into itself since it needs to solve fuxn(9) and fuxn(8) ect
1st Jun 2017, 7:32 PM
Bryan
0
This works, but I don't understand why my original doesn't. https://code.sololearn.com/c5Q3yZksW5Tb/#cpp
1st Jun 2017, 7:38 PM
Bryan
0
Also can someone help me understand when to use = vs when to use ==
1st Jun 2017, 7:38 PM
Bryan