用c语言写有理数的四则运算
时间: 2023-03-28 07:00:54 浏览: 124
可以使用结构体来表示有理数,结构体包含分子和分母两个成员变量。四则运算可以通过分别对分子和分母进行加、减、乘、除的操作来实现。具体实现可以参考以下代码:
```c
#include <stdio.h>
typedef struct {
int numerator; // 分子
int denominator; // 分母
} Rational;
// 求最大公约数
int gcd(int a, int b) {
return b == ? a : gcd(b, a % b);
}
// 化简有理数
void simplify(Rational *r) {
int g = gcd(r->numerator, r->denominator);
r->numerator /= g;
r->denominator /= g;
}
// 加法
Rational add(Rational a, Rational b) {
Rational r;
r.numerator = a.numerator * b.denominator + b.numerator * a.denominator;
r.denominator = a.denominator * b.denominator;
simplify(&r);
return r;
}
// 减法
Rational sub(Rational a, Rational b) {
Rational r;
r.numerator = a.numerator * b.denominator - b.numerator * a.denominator;
r.denominator = a.denominator * b.denominator;
simplify(&r);
return r;
}
// 乘法
Rational mul(Rational a, Rational b) {
Rational r;
r.numerator = a.numerator * b.numerator;
r.denominator = a.denominator * b.denominator;
simplify(&r);
return r;
}
// 除法
Rational div(Rational a, Rational b) {
Rational r;
r.numerator = a.numerator * b.denominator;
r.denominator = a.denominator * b.numerator;
simplify(&r);
return r;
}
int main() {
Rational a = {1, 2};
Rational b = {3, 4};
Rational c = add(a, b);
printf("%d/%d + %d/%d = %d/%d\n", a.numerator, a.denominator, b.numerator, b.denominator, c.numerator, c.denominator);
Rational d = sub(a, b);
printf("%d/%d - %d/%d = %d/%d\n", a.numerator, a.denominator, b.numerator, b.denominator, d.numerator, d.denominator);
Rational e = mul(a, b);
printf("%d/%d * %d/%d = %d/%d\n", a.numerator, a.denominator, b.numerator, b.denominator, e.numerator, e.denominator);
Rational f = div(a, b);
printf("%d/%d / %d/%d = %d/%d\n", a.numerator, a.denominator, b.numerator, b.denominator, f.numerator, f.denominator);
return ;
}
```
阅读全文