This is the message I get and no matter how much I searched, I can't seem to find the solution let alone the perfect explanation to that error.
I want the program to request a number and calculate it's factorial.
I just started learning C++. I'm a newbie.
This is my code:
#include "stdafx.h"
#include <iostream>
using namespace std;
int get_factorial(int n)
{
int factorial;
while(n > 1)
{
factorial *= --n; // the compiler, Microsoft C++ 2008 points the error to this line.
}
return factorial;
}
void main()
{
int n;
int factorial;
cout<<" Insert value :";
cin>>n;
factorial = get_factorial(n);
cout<<" The answer is "<<factorial<<endl;
So tell me, the first time you get to this bit, what value does factorial have? There's no way to tell. It could be any value. Completely random, because you didn't give the variable an initial value.
Here is how to give the variable an initial value of zero: int factorial = 0;
and here is how to give the variable an initial value of fifty-six: int factorial = 56;
Now you think about what value it should have to start, and do that.
While I'm here, this: void main()
is not C++. In C++, main returns an int, like this: int main()