设计并上机实现抽象数据类型“有理数”,有理数的基本操作包括:两个有理数的加、减、乘、除等(包括有理数的创建和输出)。
时间: 2023-03-27 16:01:56 浏览: 143
好的,我可以回答这个问题。有理数可以用分子和分母表示,我们可以设计一个结构体来表示有理数,其中分子和分母都是整数类型。有理数的加、减、乘、除等操作可以通过分别对分子和分母进行运算来实现。具体实现可以参考以下代码:
```
#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 subtract(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 multiply(Rational r1, Rational r2) {
Rational result;
result.numerator = r1.numerator * r2.numerator;
result.denominator = r1.denominator * r2.denominator;
simplify(&result);
return result;
}
// 有理数除法
Rational divide(Rational r1, Rational r2) {
Rational result;
result.numerator = r1.numerator * r2.denominator;
result.denominator = r1.denominator * r2.numerator;
simplify(&result);
return result;
}
// 输出有理数
void printRational(Rational r) {
printf("%d/%d\n", r.numerator, r.denominator);
}
int main() {
Rational r1 = {1, 2};
Rational r2 = {3, 4};
Rational r3 = add(r1, r2);
Rational r4 = subtract(r1, r2);
Rational r5 = multiply(r1, r2);
Rational r6 = divide(r1, r2);
printRational(r3);
printRational(r4);
printRational(r5);
printRational(r6);
return ;
}
```
阅读全文