[英]C Programming question about power, factorial, and combination
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.在这个问题中,我被分配到使用 for 循环的代码功率和阶乘。 And I think I have done that (they are working one by one).我想我已经做到了(他们正在一件一件地工作)。 Also in the main function, I need to calculate an equation.同样在主function中,我需要计算一个方程。 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:如果您确定要执行 integer 算术,则需要确保在除法之前分母不为零:
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)!
在外部 for 循环的第一次迭代中, i=1
,这意味着分母循环将只执行一次,将分母设置为: 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
). ,在 integer 除法中为 0(除非n=1
或n=2
)。
If you did not intend to perform integer arithmetic, then change the type of the denominator
to double
:如果您不打算执行 integer 算术,则将denominator
的类型更改为double
:
double denominator = 0, numerator = 0;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.