Can someone check this code out?

I need to write a program that displays e^x for a non-negative integer (x). The number x will from user input. It is sufficient to use 10 as a max number for n. The function factorial should have one integer parameter (n) and return one integer (n!). The function factorial should not have any output statements. The main function should call the function factorial and should do all the priniting.

Here is my code:
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
//Problem Set 9: Exercise 1
//Written by: Dylan Metz
//Course: COMSC-044

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

double factorial (double);

int main()
{
double x=1;
double n;
double exp=1;
double fac;

cout<<setiosflags(ios::fixed);
cout<<setprecision(5);

cout<<"Please enter a non-negative integer: ";
cin>>n;

while (n<0)
{
cout<<"Please enter a non-negative integer: ";
cin>>n;
}
exp+=n;
while (x>11)
{
fac=factorial (x);
x++;
exp+=pow(n,x)/fac;
}
cout<<exp;
return 0;
}
double factorial (double num)
{
double fac=1;
while (num > 0)
{
fac*=num;
num--;
}
return fac;
}


The vaiables in the code are different from the assignment.

When I input 1 so e^1 I get 2 or 2.000000. Which is different from my calculator.
Last edited on
Your while loop at line 30 requires x > 11, but it's only ever set to 1 (line 13). Lines 15 and 29 then set exp to be 2, which is printed.

Cheers,
Jim
Topic archived. No new replies allowed.