Some Assistance Please

Last week I had an assignment in my beginners C++ class, which was: "1. Write a C++ program to evaluate the following expression: (1/n!)-(x/(n-1)!) + (x2/(n-2)!) - (x3/(n-3)!) + … +/- (xn/1!) given values for x and n. These values need to be properly declared and input from the keyboard. Properly document/comment the program. Show output after execution for different values of x and n (at least 5 pairs of values). You are allowed to use only one loop construct such as for, while and do. No math or similar library functions are allowed." Since I'm a beginner, I got the homework assignment wrong, needless to say. My instructor is not of much help either since the grade is only pass/fail, so any comments as to where I went wrong in my code would be much appreciated! I'm NOT looking for the answer, JUST guidance.


# include <iostream>
using namespace std;
void main ()
{
int x,n;
cout<<"Please enter values for x,n respectively: ";
cin>>x>>n;
float product=1.0;
float sum = 0.0;
float fact=1.0;
float c = 1.0;
for (int i=1; i<=n ; i++)
{
sum = -1.0/(c*=i);
product= product *= x;
fact=fact *= (n-1);
sum=-sum + (product/fact);
}
cout<<"The answer is: "<<sum<<endl;
}
1. Please use the [ code][/code]-tag! (without the whitespace behind the first bracket)

2. What should this sum=-1.0/(c*=i)(l. 14), product= product *= x;(l. 15) and fact=fact *= (n-1);(l.16) mean?

3. You have to use + and - alternately, don't you? So you should use a if-clause.
(l. 13 - 18)
1
2
3
4
5
6
7
8
9
10
for(int i=1;i<=n;i++)
{
    sum=-1.0/(c*=i);
    product=product* =x;
    fact=fact*=(n-1);
    if(i%2==0) //every two times
        sum+=(product/fact);
    else
        sum-=(product/fact);
}


I'm only quite sure that all of this is right.

And here your code: (italic words are added from me)

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
#include <iostream>

using namespace std;

void int main (int argc, char *argv[])
{
    int x,n;
    cout<<"Please enter values for x,n respectively: ";
    cin>>x>>n;
    float product=1.0;
    float sum = 0.0;
    float fact=1.0;
    float c = 1.0;

    for (int i=1; i<=n ; i++)
    {
        sum = -1.0/(c*=i);
        product= product *= x;
        fact=fact *= (n-1);
        if(i%2==0) //every two times
            sum+=(product/fact);
        else
            sum-=(product/fact);
    }

    cout<<"The answer is: "<<sum<<endl;

    return 0;
}
Last edited on
Okay sorry about that, I'm new to this website as well. In response to bulled #2: (l. 14) is to start the function (1/n!), (l.15) is to raise x to power 1-n, and (l. 16) is to create the factorial of the denominator starting from (n-1) - 1. And yes the code has to alternate + and -. Thank you for your help, it's much appreciated!
Topic archived. No new replies allowed.