Monday, May 24, 2010

Why doesnt my C++ program work? Help!?

ok so im supposed to write a program that calculates n! using functinos, this is what i have so far.





#include %26lt;iostream%26gt;


using namespace std;





int fact(int n, Int factor, int i)


{


for (int i=1;i%26lt;=n;i++)


factor = factor * i;


return factor;


}





int main ()


{


int n, factor, i;


cout%26lt;%26lt;"Enter a number"%26lt;%26lt;"\n";


cin%26gt;%26gt;n;


factor = fact(n,factor,i);


cout%26lt;%26lt;factor;





return 0;


}





i copile it and it checks out but my answer is always zero. Can anyone see what i did wrong?

Why doesnt my C++ program work? Help!?
%26gt; i did but all i got then was an error message, NO feaken


%26gt; WAY!!!! I did before and all i got was an error message


%26gt; i did it just now again and it worked, wtf!!! My comp is


%26gt; messing with me, (Argg)





Welcome to the world of programming! It sucks! You're gonna love it...
Reply:try initializing factor to 1 before calling the function.
Reply:Change the line 'int n,factor,i;' to this:


int n,i;


unsigned long factor=1;





In your original program, 'factor' was not initialized, so the initial value could have been anything. Also, by using an unsigned long data type for 'factor', the program will allow a number up to 4294967295.


You had 'factor' as an integer, so the maximum number it can hold is 32767.
Reply:hey man what are you doing its all wrong let me write that for you. It goes like this........





# include%26lt;iostream.h%26gt;


int fact(int n)


{ int factorial=1;


for (int i=1;i%26lt;=n;i++)


{


factorial=factorial*i;


}


return factorial;


}





int main()


{


int n;


cin%26gt;%26gt;n;


int factorial=fact(n);


cout%26lt;%26lt;factorial;


return 0


}





hope it helps.


No comments:

Post a Comment