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):
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* 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. 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. But it may not produce the correct sum I'm afraid.
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.