So im supposd to write a program that calculates
the sum of 1/n! (1 divided by n factorial) , n=1 to 100
or n=1 below the Sigma sign, 100 above, 1/n1 on the right of the sigma sign
This is my program:
keep in mund C++
#include %26lt;iostream%26gt;
using namespace std;
int main ()
{
int i,fact=1,sum;
for(i=1;i%26lt;=100;i++)
{ fact = fact * i;
sum = 1/fact;
cout%26lt;%26lt;sum;
}
return 0;
}
after i compile link it and execute it i get a message saying
Arithmetic Exception (core dumped)
What is that?
Help please who ever is out there.
I cant' figure whats wrong w/my C++ program!HELP!?
This program has a lot of issues
1stly, you should 1st initialize sum to 0 and then use
sum+= 1/fact (because you want the summation and not each of them individually)
the second problem is, that you should be declaring sum as a double and not an int.
int x=1/2 //implies x=0
double x=1.0/2 //implies x=0.5
this brings me to the 3rd problem.
1/fact will always be zero since 1%26lt;fact and both are ints. you need to write that as 1.0/fact
and to wind it up, one last problem, fact(100) is a really large number. it cant be stored as an integer. I am too lazy to try, but I am pretty sure you cant store it as a long either. you will get overflows of numbers (number turning into a negative number), which will skew your results.
I am appending a similar program. see if it makes sense to you
#include %26lt;iostream%26gt;
using namespace std;
int main ()
{
int i,fact=1;
double sum=0; //sum is now double and initialized to 0
for(i=1;i%26lt;=10;i++) //10 and not 100
{
fact *= i;
sum += 1.0/fact; //adding to sum. also 1.0 and not 1
cout%26lt;%26lt;sum%26lt;%26lt;endl; //appending a newline. this helps bufferring the stream and you catch errors better
}
return 0;
}
All the best
Reply:Make sure fact is not 0 at all... I know
you intialied fact before the i loop to one...
but does it stay above 0 all the time in the loop...
usually a arithmetic expcetion means
you try to divide a 0 or...
the division symbol is not the right one..
since it's integer...
remember you are not getting integer result 1/2 is .50
here is what you can do to see what is the probem
take out the sum=1/fact for now and put a
cout %26lt;%26lt; fact %26lt;%26lt; endl; to see if fact is putting out the right numbers... if not than you know..
if it seems right...
put back the sum=1/fact;
but check to see if you are allowed to use / because you are getting a decimal value and you may have to use..
the var real...
Reply:try unsigned long i,fact=1,sum;
instead of int i,fact=1,sum;
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment