PDA

View Full Version : Help with factorial function


AbsoluteZero
09-10-2003, 03:07 PM
Hi can anyone help me using the factorial function?
Heres the code:

#include <iostream.h>
#include <math.h>


int main() {
double sen;
double sen2;
int elemento=1;
double x;


long double fnction;
int z=3;
int resultado;

int factorial(int n)

x=0.523598;
sen = sin(0.523598);
cout<<"El seno de 30 grados es "<<sen<<endl;
sen2=0.5235969;

resultado=sen-sen2;
while (resultado>0.000001) {

fnction=-(pow(x,z))/(factorial(z));
sen2=30+fnction;
elemento++;
z+=2;

fnction=-fnction;

}


cout<<"Se requieren "<<elemento-1<<" elemento(s)"<<endl;

}

im trying to get an error of less than 0.000001 for the sine function. I have to determine the number of elements needed to do this. I think theres an error in how im using the factorial function. Thanks

DNAunion2000
09-10-2003, 08:09 PM
/*DNAunion*/ You can't define or declare a function inside of another function, so int factorial(int n) is a problem. It looks like a function prototype: if that's not what you are trying to do with that line, then what?

Jamaican
09-12-2003, 05:54 PM
I really don't remember any function called "factorial()".
That is why you're havbing problems with it.
you cannot use it as a function because it isn't one.
thus "int factorial(int n)" is a declaration
what you need to do is define the function factorial()

Its not the best but here is a definition, put it at the bottom of main():


int factorial (int n)
{
if (n<1)
return -1;

else
return (n*factorial(n-1));

}

Jamaican
09-13-2003, 01:49 AM
I Have "optimize" your code some what. I really don't know what you want it do, but at the piont there are a lot of things that you can take out.
here is the rework:


#include <iostream>
#include <math.h>
using namespace std;

int main()
{
double sen, sen2, x, resultado;
int elemento=0, z=3;
long double fnction;

int factorial(int n); //this is nothing but a declaration
x=0.523598;
sen = sin(0.52359);
cout<<"El seno de 30 grados es "<< sen << endl;
sen2=0.5235969;

resultado = sen2 - sen; // you had sen-sen2 which assigned a negative
//number to resultado. I switched it to
//give a positive number
while (resultado>0.000001) //since it was a nagative number, this condition
// could not be reached.
{

--resultado; //After switching the sen2 and sen I placed this
//down here to meetthe condition that will stop the
//while loop
fnction =(pow(x,z))/(factorial(z));
sen2=30+fnction;
elemento++;
z+=2;

fnction=-fnction; //what is this for? it surves no perpose here at the point //neither does z+=2.
}
cout<<"\nSe requieren "<<elemento<<" elemento(s)"<<endl;
return 0;
}

// This is the factorial() Function definition
int factorial (int n)
{
if (n<1)
return -1;
else
return n*factorial(n-1);
}