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;
}
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!