I have some code where I want to print as many numbers in the Fibonacci sequence as defined by "totalNumbers". I cannot get it to compile though, it has numerous errors. I am not sure if my for statement i<=20 is the totalNumbers that my instructor wants to be changed by to allow more or less numbers. Anyone know if this is right or why my code won't run? How would I convert my code to alow the parameter of totalNumbers to be what changes how many numbers print in the sequence?
@closed account 5a8Ym39o6 It works, but you removed my void function, which I am supposed to use. Also, I needed to make the "totalNumbers" the variable to change, instead of my for loop. Any idea how I could do it? Basically, instead of changing the amount of times it prints using my loop, I want to use int totalNumbers.
You could also pass the argument to the function by reference, that way it's value is altered in main.
void Fibonacci(constint& totalNumbers);
Not sure if you have learnt about references yet, but it is one way of achieving what you want. And you can avoid having the function printing things. Ideally functions should do one conceptual thing: In this case calculate the Fibonacci number. The responsibility to print the result should be elsewhere.
Also, rather than have "magic numbers" in your code, make them variables and refer to them in the code, like what FurryGuy did with the position variable.
constunsignedshortint totalNumbers = 20;
That way you can change how any numbers are produced in one place. Note you are supposed to make use of the function parameter, not limit the loop with some other value.
Also totalNumbers needs to be checked, there is a maximum size it can be before it causes an overflow of the type being used. Notice that FurryGuy usedunsignedlonglong? That is the largest unsigned type the system has. There are other names for it, but your teacher will ask where you learnt them.
It is an assignment, but I think his professor wouldn't ask him that much.
How do you know? Passing by reference is something that might be taught in the first 3 or 4 weeks. The fact that a void function was asked for was a big clue. The other things beginners often miss, but might worth some brownie points - especially the concept of checking the validity of a value.
My use of the position variable was simply a hold-over from a Fibonacci program that the user would enter a number and the program would output that number's Fibonacci number.
Regarding making the function use a reference, I considered doing that, but chose to move the output statements into the function itself.
Yes, that over-clutters the function but was a quick off-the-cuff choice that I wouldn't have likely done in a real-world situation.
Checking the output for accuracy/overflow is something I should have done, though. Mea Culpa.