[英]Addition of fractions in C: Floating point exception
I'm writing a little program working with fractions: 我正在编写一个处理分数的小程序:
struct fraction
{
int num;
int den;
};
typedef struct fraction FRAC;
I use a least common multiple function to add two fractions (without simpilfying them afterwards): 我使用一个最不常用的多重函数添加两个分数(此后不进行simpilfying):
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;
}
Given an array of FRAC
I want to calculate the sum with following function: 给定一个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;
}
However this expression 但是这个表达
print(*fraction_sum(fractions, N));
returns the error 返回错误
Floating point exception (core dumped)
Any ideas? 有任何想法吗? Is there a more elegant way to do this? 有没有更优雅的方法可以做到这一点?
看起来您正在被零除。
将初始化更改为
sum->den = 1;
You are dividing by zero . 您正在除以零 。
The first time u call function add, the parameter a has both its num and den equal to zero. u首次调用函数add时,参数a的num和den都等于零。 This causes that exception you are getting later in this expression. 这将导致您稍后在此表达式中得到该异常。
int la = l/a.den;
Initializing b.den to 1 should stop your program from crashing. 将b.den初始化为1应该可以防止程序崩溃。 But it may not produce the correct sum I'm afraid. 但恐怕它可能无法产生正确的金额。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.