用C语言实现有理数抽象类型实现有理数的创建和输出包括有理数的加减乘除
时间: 2023-03-28 15:01:53 浏览: 148
您好,我可以回答您的问题。以下是用 C 语言实现有理数抽象类型的代码:
```c
#include <stdio.h>
typedef struct {
int numerator; // 分子
int denominator; // 分母
} Rational;
// 求两个整数的最大公约数
int gcd(int a, int b) {
if (b == ) {
return a;
} else {
return gcd(b, a % b);
}
}
// 化简有理数
void simplify(Rational *r) {
int g = gcd(r->numerator, r->denominator);
r->numerator /= g;
r->denominator /= g;
}
// 创建有理数
Rational create_rational(int numerator, int denominator) {
Rational r = {numerator, denominator};
simplify(&r);
return r;
}
// 输出有理数
void print_rational(Rational r) {
printf("%d/%d", r.numerator, r.denominator);
}
// 加法
Rational add_rational(Rational r1, Rational r2) {
int numerator = r1.numerator * r2.denominator + r2.numerator * r1.denominator;
int denominator = r1.denominator * r2.denominator;
return create_rational(numerator, denominator);
}
// 减法
Rational sub_rational(Rational r1, Rational r2) {
int numerator = r1.numerator * r2.denominator - r2.numerator * r1.denominator;
int denominator = r1.denominator * r2.denominator;
return create_rational(numerator, denominator);
}
// 乘法
Rational mul_rational(Rational r1, Rational r2) {
int numerator = r1.numerator * r2.numerator;
int denominator = r1.denominator * r2.denominator;
return create_rational(numerator, denominator);
}
// 除法
Rational div_rational(Rational r1, Rational r2) {
int numerator = r1.numerator * r2.denominator;
int denominator = r1.denominator * r2.numerator;
return create_rational(numerator, denominator);
}
int main() {
Rational r1 = create_rational(1, 2);
Rational r2 = create_rational(2, 3);
Rational r3 = add_rational(r1, r2);
Rational r4 = sub_rational(r1, r2);
Rational r5 = mul_rational(r1, r2);
Rational r6 = div_rational(r1, r2);
printf("r1 = ");
print_rational(r1);
printf("\n");
printf("r2 = ");
print_rational(r2);
printf("\n");
printf("r1 + r2 = ");
print_rational(r3);
printf("\n");
printf("r1 - r2 = ");
print_rational(r4);
printf("\n");
printf("r1 * r2 = ");
print_rational(r5);
printf("\n");
printf("r1 / r2 = ");
print_rational(r6);
printf("\n");
return ;
}
```
希望能够帮到您!
阅读全文