用C语言设计实现抽象数据类型“有理数”。基本操作包括有理数的加法、减法、乘法、除法,以及求有理数的分子、分母。
时间: 2023-03-29 11:02:46 浏览: 293
可以使用结构体来表示有理数,结构体中包含分子和分母两个整型变量。加法、减法、乘法、除法可以通过分别对分子和分母进行运算得到结果。求分子和分母可以直接访问结构体中的成员变量。具体实现可以参考以下代码:
```
#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 r1, Rational r2) {
Rational result;
result.numerator = r1.numerator * r2.denominator + r2.numerator * r1.denominator;
result.denominator = r1.denominator * r2.denominator;
simplify(&result);
return result;
}
// 有理数减法
Rational sub(Rational r1, Rational r2) {
Rational result;
result.numerator = r1.numerator * r2.denominator - r2.numerator * r1.denominator;
result.denominator = r1.denominator * r2.denominator;
simplify(&result);
return result;
}
// 有理数乘法
Rational mul(Rational r1, Rational r2) {
Rational result;
result.numerator = r1.numerator * r2.numerator;
result.denominator = r1.denominator * r2.denominator;
simplify(&result);
return result;
}
// 有理数除法
Rational div(Rational r1, Rational r2) {
Rational result;
result.numerator = r1.numerator * r2.denominator;
result.denominator = r1.denominator * r2.numerator;
simplify(&result);
return result;
}
int main() {
Rational r1 = {2, 3};
Rational r2 = {3, 4};
Rational r3 = add(r1, r2);
Rational r4 = sub(r1, r2);
Rational r5 = mul(r1, r2);
Rational r6 = div(r1, r2);
printf("%d/%d + %d/%d = %d/%d\n", r1.numerator, r1.denominator, r2.numerator, r2.denominator, r3.numerator, r3.denominator);
printf("%d/%d - %d/%d = %d/%d\n", r1.numerator, r1.denominator, r2.numerator, r2.denominator, r4.numerator, r4.denominator);
printf("%d/%d * %d/%d = %d/%d\n", r1.numerator, r1.denominator, r2.numerator, r2.denominator, r5.numerator, r5.denominator);
printf("%d/%d / %d/%d = %d/%d\n", r1.numerator, r1.denominator, r2.numerator, r2.denominator, r6.numerator, r6.denominator);
printf("分子:%d,分母:%d\n", r1.numerator, r1.denominator);
return ;
}
```
阅读全文