Function question

I'm new to the website, but have a question about functions. I been working on a program for my class where we have to program the Taylor series without using <cmath>. In this program the user has to input how many times they want to calculate the sum(n times). However when i ask the user to input n it doesn't go to the other functions. I know the factorial function is right, I'm not so sure about my numerator.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
int main()
{
	double x;
	int n;
	cout << "Enter the number of how many times you want to calculate the sum of exponentials" << endl;
	cin >> n;
	x = numsum(x)/ fact(factorial);


	cout << "This is the sum of the exponential " << x << endl;

	return 1;
}
double numsum(double A)
{
	
	int n;
	int i = 1;
	double sum = 1;
	while(i <= n)
	{
		sum = sum * i;
		i++;
	}
	return sum;

}
double fact(double B)
{
	double factorial = 1;
	int j = 1;
	while(j <= n)
	{
		factorial =*j;
		j++;
	}
	return factorial;

}


So can someone please help tell me why it's not going to my other functions please.
You are defining your functions after main and you have no prototypes declared. If you call a function in main without having the function defined before main or having a prototype before main, the compiler won't know what you're trying to do and return an error. Just put your functions before main or use prototypes.
Basically the compiler must read everything before it can be used.
If you need functions in main but want them to be placed lower in the program, or somewhere completely different then you must have 'prototypes' before they're needed.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
double numsum(double A);//function prototype 1
double fact(double B);//function prototype 2

int main(){
    double x;
    int n;
    cout << "Enter the number of how many times you want to calculate the sum of exponentials" << endl;
    cin >> n;
    x = numsum(x)/ fact(factorial);
    cout << "This is the sum of the exponential " << x << endl;
    return 1;
}
double numsum(double A){//function 1
    int n;
    int i = 1;
    double sum = 1;
    while(i <= n){
        sum = sum * i;
        i++;
    }
    return sum;
}
double fact(double B){//function 2
    double factorial = 1;
    int j = 1;
    while(j <= n){
        factorial =*j;
        j++;
    }
    return factorial;
}


P.S. I don't like your 'tab' spacing so I fixed it XD (4 space standard)
Last edited on
Try numsum(n) rather than numsum(x)
Also, inside the function, you need to use the parameter which was passed, such as A or B
Last edited on
Sorry about this, but i do have them initialized the functions that is. The thing is that within my while my loop
1
2
3
4
5
while(i <= n)/////// here
{
    sum = sum * i;
    i++;
}

the user is suppose to input n in the main one, but both functions don't recognize n and i don't know why.
@@chervil
what do you mean? I am really new to new this sorry.
I get these as errors
error C2065: 'b' : undeclared identifier for line 7
error C2065: 'n' : undeclared identifier for line 20
@jlucero77
I started to write an explanation, but it began to sound like nonsense, even to me, so instead I'll refer you to the tutorial pages:

http://www.cplusplus.com/doc/tutorial/functions/


Scope of variables
http://www.cplusplus.com/doc/tutorial/variables/

I think n should be a global variable (declared outside main()).



and

factorial part:

factorial *=j;

Last edited on
fx11 wrote:
I think n should be a global variable (declared outside main()).

I disagree. That's the wrong solution, it leads to all sorts of unexpected side-effects.

The correct approach is to pass value(s) into the function via the parameters, and return the result using the return statement.
@Chervil, thanks. But I think that at this little code global variables are not so confusing. At a bigger code ..., that's another case.

@jlucero77
I don't know exactly to which function would you like to calculate its Taylor series?
If I know well, Taylor series has infinite members to be added.
You may want to calculate the Taylor polynomial of degree N of the exponential function.
If that's true then take a look at my code, and test it:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
// http://en.wikipedia.org/wiki/Taylor_polynomial
// http://math.tutorvista.com/discrete-math/exponential-series.html

// Taylor series of the exponential function:
// exp(x) = e^x = SZUMMA {n=0, inf}  ( x^n / n! )

// Taylor polynomial of degree N (N>0) of the exponential function:
// e^x = 1 + SZUMMA {n=1, N}  ( x^n / n! )

#include <iostream>
#include <cstdlib>
#include <cmath> // just for checking purposes of exp(x)
using namespace std;

double x=1;
int N=1;
int n=1;

double Numr();
double DeNumr();

int main() {
    double sum=1;
    cout << "Taylor polynomial of degree N (N>=0) of the exponential function: " << endl;
    cout << "e^x = 1 + SZUMMA {n=1, N}  ( x^n / n! ) " << endl << endl;
    cout << "Type N [N>=0]: ";
    cin >> N; cout << endl;
    cout << "Type x: ";
    cin >> x; cout << endl;

    if (N==0)   sum = 1;

    else if(N>0)
        for(n=1;n<=N;n++)
            sum += Numr() / DeNumr();
    else  {
        cout<< "Wrong input!" << endl;
        exit (-1);
    }
    cout << "The sum of the Taylor polynomial of degree " << N
         << "\nof the exponential function (e^x) is " << sum << endl<<endl;
    cout << "Checking the results:\ne^"<<x<<" = " << exp(x) << endl<<endl;

    return 0;
}

// e^x = 1 + SZUMMA {n=1, N}  ( x^n / n! )

double Numr() {
    double xAdn = 1;
    for(int i=1; i<=n; i++)
        xAdn *= x;
    cout<<"Numerator: "<<xAdn<<'\t';
    return xAdn;
}

double DeNumr() {
    double nFact = 1;
    for(int i=1; i<=n; i++)
        nFact *= i;
    cout<<"DeNumerator: "<<nFact<<endl<<endl;
    return nFact;
}


Last edited on
fx11 wrote:
@Chervil, thanks. But I think that at this little code global variables are not so confusing. At a bigger code ..., that's another case.


I don't wish to cause offence, but I still disagree, and I'll briefly explain why.

The problem with that point of view is it doesn't help the OP to understand what was wrong with the original code. There are various errors in the way in which the functions were used.

Simply switching to a different design doesn't give any explanation of what was wrong in the first place.

I accept that I too have failed to give a proper explanation. I will follow up with a proper explanation later and hopefully give the OP a better foundation from which to continue with further progress, not just in this program, but in learning C++ as a whole.

you don't need to use 2 functions or 3 global variables to accomplish this.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <iostream>
#include <cmath>  //checking purpose
using namespace std;

double ex(double x, int n);

int main()
{
  // hard coded values for testing purpose
  double x = 2.5;
  int n = 20;
  
  cout << ex(x,n) << endl;
  cout << exp(x) << endl;
}

double ex(double x, int n)
{
  double ret = 1;
  while(n)
  {
    double term = x;
    for (int i=2; i<=n; ++i) term *= x/i;
    ret += term;
    --n;
  }
  return ret;
}
Last edited on
jlucero77 wrote:
So can someone please help tell me why it's not going to my other functions please.

The original code and this question are deeply puzzling to me. The original code doesn't compile, not even after adding the missing lines before the start of main()

And because it doesn't compile, in my simplistic way of thinking, there is no way of knowing what it does or doesn't do when it is run. So the code posted above cannot be the same code as that for which the question was asked, surely?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#include <iostream>

using namespace std;

double numsum(double A);
double fact(double B);

int main()
{
	double x;
	int n;
	cout << "Enter the number of how many times you want to calculate the sum of exponentials" << endl;
	cin >> n;
	x = numsum(x)/ fact(factorial);

	cout << "This is the sum of the exponential " << x << endl;

	return 1;
}

double numsum(double A)
{
	int n;
	int i = 1;
	double sum = 1;
	while(i <= n)
	{
		sum = sum * i;
		i++;
	}
	return sum;
}

double fact(double B)
{
	double factorial = 1;
	int j = 1;
	while(j <= n)
	{
		factorial =*j;
		j++;
	}
	return factorial;
}

Here are the problems with compiling this code.
At line 14, the variable factorial is undeclared.
At line 38, while(j <= n) the variable n is undeclared.
That can be remedied by changing that line to while(j <= B)
At line 40, factorial =*j; this line is trying to calculate the value of *j and assign it to factorial. It should of course read factorial *= j;

Having made those changes, the code will now compile, but there are sill warning messages which should be observed and corrected.

At line 21, the function receives a parameter A double numsum(double A)
but nowhere in the function is the parameter A actually used. It is never mentioned again. And that is one of the important things about the way functins are used.

At line 10, in function main(), there is this :
 
    x = numsum(x)/ fact(factorial);

Here, the variable x is passed as an input parameter to the function numsum. The value of x is copied to the variable A and then inside function numsum, that variable should be used.

There is another problem here. In function main(), x has not yet been assigned any value, so it doesn't make sense to pass it as a parameter. As was already mentioned, variable factorial not only hasn't been assigned a value, it doesn't even exist, so that doesn't make sense either.

All of this suggests the basic concepts of how to call a function using parameters is not fully understood, which is why I suggested (and now repeat) my recommendation to read the tutorial page on functions. http://www.cplusplus.com/doc/tutorial/functions/

All of this is really just the basic concepts, and until it is understood reasonably well, it will be difficult to move on to more advanced topics.
I hear what others have said, particularly the version posted by tntxtnt which is roughly (but not exactly) how I would approach this myself (I wouldn't use a for loop at line 23, one loop is sufficient).

Anyway, here is a working version, using functions. it may be wasted effort on my part, I only hope the OP will take on board not so much the code as a whole, but more importantly, the details of how it all fits together:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
#include <iostream>

    using namespace std;

double numsum(double A, int n);
double fact(double B);
double exponential(double x, int n);

int main()
{
    double x;
    int n;

    cout << "  This progam calculates the exponential function e^x \n"
         << "  using the Taylor series to a specified number of terms\n" << endl;

    cout << "  Enter the value of x: " << flush;
    cin >> x;

    cout << "  Enter the number of terms: " << flush;
    cin >> n;

    double result = exponential(x,n);

    cout.precision(15);
    cout << "\n  This is the sum of the series : " << result << endl;

    return 1;
}

// numsum - calculate A raised to the power n
double numsum(double A, int n)
{
    double sum = 1;

    int i=1;
    while(i <= n)
    {
        sum = sum * A;
        i++;
    }

    return sum;
}

// fact - calculate factorial of B
double fact(double B)
{
    double factorial = 1;

    int j = 1;
    while(j <= B)
    {
        factorial *= j;
        j++;
    }

    return factorial;
}

// exponential - calculate the exponential function of x
//               using the sum of n terms of the Taylor series.
double exponential(double x, int n)
{
    double total = 0;

    for (int i=0; i<n; i++)
    {
        total += numsum(x, i) / fact(i);
    }

    return total;
}

Output:
  This progam calculates the exponential function e^x
  using the Taylor series to a specified number of terms

  Enter the value of x: 1
  Enter the number of terms: 20

  This is the sum of the series : 2.71828182845905

Last edited on
@@chervil
You been a great help thank you. I read the tutorial but i cant seem to grasp the concept of functions. and in the code you posted in the function double numsum what does A equal? And is it possible to call another function within a function like you did in the double exponential?
I read the tutorial but i cant seem to grasp the concept of functions.

When it comes to programming, you need to combine reading with hands-on practice. I think there are a few examples in the tutorial, try them out, experiment, see what happens when you change things. Don't be afraid of making mistakes, that's the best way to learn. What I do when learning a new topic is to add lots of cout statements scattered at strategic points throughout the code, to display the values of each variable.

and in the code you posted in the function double numsum what does A equal?

Look at function main() first. There, the function exponential(x,n) is called. Inside that function, the variables x and n have the same values as those supplied by the user. (Though technically they are separate variables, they are copies of the user input).

There is a for loop, the function numsum(x, i) is called. The value of x is still the same one which was supplied by the user. The value of i will change with each iteration of the loop.

Inside the function numsum(double A, int n), each parameter again receives a copy of the value of the parameter which was used in the function call.
Therefore the value of A is a copy of the value of x
and the value of n is a copy of the value of i

Notice that the names of the variables need not be the same - often a function may be called many times at different points in the code, so it's very natural that the variable name in the calling code can vary.

However the position of the variable is important. Since A is the first parameter in the function definition, it receives the first parameter from the function call, and so on.

And is it possible to call another function within a function like you did in the double exponential? That's a rhetorical question isn't it? Have you tried compiling and running the code?
Topic archived. No new replies allowed.