Tuesday, July 28, 2009

C++ function help?

Here is my code








[code]


#include %26lt;iostream%26gt;


#include %26lt;iomanip%26gt;


using namespace std;





double factorial(double n)


{


factorial=n;





while (n%26gt;1)


{


factorial=(factorial*(n-1));


n--;


}


return factorial;


}





int main()


{


double n;


double factorial;





cout%26lt;%26lt;"Enter the value for which you want its factorial: \n";


cin%26gt;%26gt;n;





cout%26lt;%26lt;"The factorial is "%26lt;%26lt;factorial(n)%26lt;%26lt;endl;





return 0;


}


[/code]





I know the factorial function is right because when I include it in main() it works on its own, but referencing it as a function is causing some error problems:





error C2659: '=' : function as left operand





error C2296: '*' : illegal, left operand has type 'double (__cdecl *)(double)'





error C2440: 'return' : cannot convert from 'double (__cdecl *)(double)' to 'double'. There is no context in which this conversion is possible





error C2064: term does not evaluate to a function taking 1 arguments.





Any ideas as to what I did wrong?

C++ function help?
When referencing this function, have you previously created/included a function prototype?





EDIT: Oh, duh - "factorial" is not a global variable. You have not defined the variable type for "factorial" within the function factorial().





Hint: instead of factorial=n; write: double factorial=n;
Reply:I think you are confusing the compiler by trying to use the same name "factorial" both for the function that takes a double and returns a double, AND also as a local variable.





In main, you don't even need a local variable called factorial, so you can delete the line





double factorial;





In the factorial function, I would add a declaration





double answer;





Then replace lines like





factorial=n





with





answer = n





and so on. That way "answer" is your local variable, which is declared as such and is distinct from "factorial" the function, which is defined above main.
Reply:double factorial(double n)


{


factorial=n;





Honey, look at what you are doing. You have a FUNCTION named "factorial". Now in the first line of that function, you are trying to assign a double value "n" to that FUNCTION. That's wrong in about 10 different ways. The first two errors you are getting are two of the ways in which this is wrong. You can't have a function on the left side of an assignment statement. And even if you could do that, the types on the left and right side of your assignment statement don't match.
Reply:You really got some very good answers already. I would just like to add a thing. In your function factorial, why are you assigning the value of n to factorial?


You can replace factorial with n itself, as n is a local variable to that function.


Hope this helps a bit!


Good Luck!


No comments:

Post a Comment