#include <iostream>
usingnamespace std;
int main (int argc, char *argv[])
{
int x,n;
cout<<"Please enter values for x : ";
cin>>x;
cout<<"Please enter values for n : ";
cin>>n;
float product=2.0;
float sum = n;
float fact=2.0;
float c = 1.0;
for (int i=2; i<=n ; i++)
{
sum = 2.0/(x-n);
product= product *= i;
fact=fact *=i/(x-2);
if(i%2==0) //every two times
sum+=(product/fact);
else
sum-=(product/fact);
}
cout<<"The answer is: "<<sum<<endl;
system("pause");
return 0;
}
Hi, it would help us help you, if you put [code] and [/code] tags around your code, to let it be properly formatted. You can still edit your post and add them now.
What input are you entering for x and n?
And can you explain specifically what instructions you're trying to tell the computer to do on these two lines?
1 2
product= product *= i;
fact=fact *=i/(x-2);
You should turn on warnings for your compiler, your code has undefined behavior
19:30: warning: operation on 'product' may be undefined [-Wsequence-point]
20:28: warning: operation on 'fact' may be undefined [-Wsequence-point]
14:11: warning: unused variable 'c' [-Wunused-variable]
Assuming the change in my previous post was applied (I don't know if that's actually what you intend):
Let's say x = 5, n = 4.
i =2
sum = 2.0 / (5 - 4) = 2.0 / 1 = 2.0
fact *= i/(x-2); --> fact = fact * (2 / 3)
2 / 3 is integer division, so you're doing fact = fact * 0 essentially.
Then you divide by fact... and boom -- you get infinity.
If you still want to do division, but not integer division, then do fact *= static_cast<double>(i)/(x-2);
Again... not sure if that's actually what you intend.
You are also re-assigning "sum" each iteration within the loop. Probably not what you want.
______________________________________
What would really, really help is if you gave us some test cases. Because you haven't made it clear what you're trying to do. Because a normal factorial isn't a function of two variables.
Given: x = 5, n = 4, what should sum be?
Given: x = 6, n = 4, what should sum be?
Given: x = 6, n = 5, what should sum be?
etc.