你的错误:
1. 如 3 楼 pangding 所言,四则运算的函数怎么能不要参数呢?
2. 分数的四则运算过程必须分别计算分子和分母,你写的函数怎么能把自己定义的类当做 float 类型来对待呢?
你先去把基础知识好好的学一下吧,把最基本的概念搞清楚。
下面是个非常简单的 c 代码,看一下吧
程序代码:
#include <stdio.h>
#include <math.h>
typedef struct {
int n, d;
} fraction;
void red_frac(fraction * f) {
int i;
for (i = 2; i <= abs(f->n) && i <= abs(f->d); i++) {
while (f->n % i == 0 && f->d % i == 0) {
f->n /= i;
f->d /= i;
}
}
if ((f->n < 0 && f->d > 0) || (f->n >0 && f->d < 0)) {
f->n = -abs(f->n);
} else {
f->n = abs(f->n);
}
f->d = abs(f->d);
}
void set_frac(fraction * f, int n, int d) {
f->n = n;
f->d = d;
red_frac(f);
}
void add_frac(fraction * r, fraction lop, fraction rop) {
r->n = lop.n * rop.d + lop.d * rop.n;
r->d = lop.d * rop.d;
red_frac(r);
}
void sub_frac(fraction * r, fraction lop, fraction rop) {
r->n = lop.n * rop.d - lop.d * rop.n;
r->d = lop.d * rop.d;
red_frac(r);
}
void mul_frac(fraction * r, fraction lop, fraction rop) {
r->n = lop.n * rop.n;
r->d = lop.d * rop.d;
red_frac(r);
}
void div_frac(fraction * r, fraction lop, fraction rop) {
r->n = lop.n * rop.d;
r->d = lop.d * rop.n;
red_frac(r);
}
void put_frac(fraction f) {
printf("(%d/%d)", f.n, f.d);
}
int main() {
fraction a, b, c;
set_frac(&a, 15, 25);
set_frac(&b, -42, 35);
add_frac(&c, a, b);
put_frac(a), printf(" + "), put_frac(b), printf(" = "), put_frac(c), printf("\n");
sub_frac(&c, a, b);
put_frac(a), printf(" - "), put_frac(b), printf(" = "), put_frac(c), printf("\n");
mul_frac(&c, a, b);
put_frac(a), printf(" * "), put_frac(b), printf(" = "), put_frac(c), printf("\n");
div_frac(&c, a, b);
put_frac(a), printf(" / "), put_frac(b), printf(" = "), put_frac(c), printf("\n");
return 0;
}
[
本帖最后由 voidx 于 2011-4-20 23:31 编辑 ]