我正在编写一个使用分数的小程序:
struct fraction
{
int num;
int den;
};
typedef struct fraction FRAC;
我使用最小公倍数函数来添加两个分数(之后不简化它们):
FRAC *add (FRAC a, FRAC b)
{
int l = lcm(a.den, b.den);
FRAC *sum;
sum = malloc(sizeof(FRAC));
sum->den = l;
int la = l/a.den;
int lb = l/b.den;
sum->num = a.num*la + b.num*lb;
return sum;
}
给定一个数组,FRAC
我想用以下函数计算总和:
FRAC* fraction_sum (FRAC *a, unsigned int size)
{
int i;
FRAC* sum = malloc(sizeof(FRAC));
sum->num = 0;
sum->den = 0;
for (i = 0; i < size; i++)
{
FRAC b = {sum->num, sum->den};
sum = add(b,a[i]);
}
return sum;
}
然而这个表达
print(*fraction_sum(fractions, N));
返回错误
Floating point exception (core dumped)
有任何想法吗?有没有更优雅的方法来做到这一点?