I have been assigned a question about solving an equation with power factorial and combination. In this question, I was assigned to code power and factorial with a for loop. And I think I have done that (they are working one by one). Also in the main function, I need to calculate an equation. So here is my code, it looks right to me. but eventually I am getting a "Floating point exception (core dumped)" error. Any help can be nice, I actually don't want the right answer, if you can explain why am I getting this error, that would be helpful. Thank you. (I cannot upload a photo because of reputation things if there is a way to share photo I will.)
#include <stdio.h>
int factorial(int n){
int i,result=1;
for(i=1; i<=n; ++i){
result = result*i;
}
return result;
}
int power(int x,int y){ // base -> x , exponent -> y
int result=1;
for(int i=1;i<=y;i++) // multiply x, y times
result*=x;
return result;
}
int combination(int n,int r){
return factorial(n)/(factorial(r)*factorial(n-r));
}
int main()
{
double ans=0;
int n;
printf("Enter n : ");
scanf("%d",&n);
for(int i=1;i<=n;i++){
int denominator = 0,numerator = 0; // set denominator, numerator to 0 because we are going to add to them
for(int z=1;z<=n-i;z++)
numerator += power(i,z);
for(int j=1;j<=i;j++)
denominator += ((power(j,n)*combination(n,j))/factorial(n));
ans = ans + (numerator/denominator);
}
printf("Resut is : %f",ans);
return 0;
}
If you are sure you want to perform integer arithmetic, you need to ensure the denominator is not zero before the division:
if (denominator != 0)
ans = ans + (numerator/denominator);
In the first iteration of the outer for loop, i=1
, which means the denominator loop will execute only once, setting the denominator to: 1^n * C(n 1) / n! = 1/(n-1)!
1^n * C(n 1) / n! = 1/(n-1)!
, which is 0 in integer division (unless n=1
or n=2
).
If you did not intend to perform integer arithmetic, then change the type of the denominator
to double
:
double denominator = 0, numerator = 0;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.