Hello, this is a homework problem, but I can't find the problem with my program. My TA who is supposed to help me couldn't figure it out either. -.- First of all, I know there is a problem with the factorials. It only outputs the right answer up to n=6 for the sin function and n=10 for the exponential function. I'm avoiding that issue until I resovle this one. The problem I'm trying to figure out is with passing the values by reference. When I call the values from the main function, all of the 'finalvalue' answers that were previously correct are changed. Any help is sincerely appreciated! I am just learning C++ and this is my first attempt with functions so please be simple.
#include <iostream>
#include <cmath>
using namespace std;
double factorial(int);
void sin (double, int, double&);
void exponential (double, int, double&);
int main ()
{
int choice, n;
double x, finalvalue;
cout<<"Select the function you wish to evaluate." <<endl;
cout<<"1) sin x" <<endl;
cout<<"2) e^x" <<endl;
cin>>choice;
cout<<"Enter the value of x you wish to evaluate." <<endl;
cin>>x;
cout<<"Enter the number of terms in the series." <<endl;
cin>>n;
if(choice==1) {
sin(x,n,finalvalue);
cout<<finalvalue <<endl;
}
else if (choice==2) {
exponential(x,n,finalvalue);
cout<<finalvalue <<endl;
}
else {
cout<<"You have entered an incorrect value. Please enter 1 or 2." <<endl;
}
system ("PAUSE");
return 0;
}
double factorial(int n)
{
int i=0, fact=1;
if(n<=1)
{
return(1);
}
else
{
for (i=1; i<=n; i++)
{
fact=fact*i;
}
return(fact);
}
}
void sin (double a,int b,double& finalvalue) {
int i;
double f=-1;
double answer, q, z;
for(i=0; i<=b; i++)
{
q=((2*i)+1);
z=factorial(q);
cout<<z <<endl;
answer=(pow(f,i)/z)*pow(a,q);
cout<<answer <<endl;
finalvalue+=answer;
cout<<finalvalue <<endl;
}
return; }
void exponential (double a, int b, double& finalvalue) {
int i;
double z, answer;
for (i=0; i<=b; i++)
{
z=factorial(i);
cout<<z <<endl;
answer=pow(a,i)/z;
cout<<answer <<endl;
finalvalue+=answer;
cout<<finalvalue <<endl;
}
return; }