试仿照三元组的抽象数据类型分别写出抽象数据类型复数和有理数的定义,使用c语言实现,要求能实现加减乘除,并返回数据结果
时间: 2024-10-08 08:03:50 浏览: 29
首先,让我们定义两个抽象数据类型:复数(Complex Numbers)和有理数(Rational Numbers)。这两个ADT(Abstract Data Type)都包含一个数值部分以及相关的操作。
**抽象数据类型:复数 (Complex)**
```cpp
typedef struct Complex {
double real; // 实部
double imag; // 虚部
} Complex;
```
对于复数,我们可以实现基本的算术运算:
```cpp
// 加法
Complex add(Complex c1, Complex c2) {
return (Complex) {c1.real + c2.real, c1.imag + c2.imag};
}
// 减法
Complex subtract(Complex c1, Complex c2) {
return (Complex) {c1.real - c2.real, c1.imag - c2.imag};
}
// 乘法
Complex multiply(Complex c1, Complex c2) {
double real = c1.real * c2.real - c1.imag * c2.imag;
double imag = c1.real * c2.imag + c1.imag * c2.real;
return (Complex) {real, imag};
}
// 除法
Complex divide(Complex c1, Complex c2) {
double denominator = c2.real * c2.real + c2.imag * c2.imag;
if (denominator == 0)
return NULL; // 防止除以零
double real = (c1.real * c2.real + c1.imag * c2.imag) / denominator;
double imag = (c1.imag * c2.real - c1.real * c2.imag) / denominator;
return (Complex) {real, imag};
}
```
**抽象数据类型:有理数 (Rational)**
```cpp
typedef struct Rational {
int numerator; // 分子
int denominator; // 分母
} Rational;
// 简化分数(如果有共同因子)
void simplify(Rational* r) {
int gcd = __gcd(r->numerator, r->denominator);
r->numerator /= gcd;
r->denominator /= gcd;
}
// 加法
Rational add(Rational r1, Rational r2) {
int new_numerator = r1.numerator * r2.denominator + r2.numerator * r1.denominator;
int new_denominator = r1.denominator * r2.denominator;
simplify(&new_numerator, &new_denominator);
return (Rational) {new_numerator, new_denominator};
}
// 减法
Rational subtract(Rational r1, Rational r2) {
int new_numerator = r1.numerator * r2.denominator - r2.numerator * r1.denominator;
int new_denominator = r1.denominator * r2.denominator;
simplify(&new_numerator, &new_denominator);
return (Rational) {new_numerator, new_denominator};
}
// 乘法
Rational multiply(Rational r1, Rational r2) {
int new_numerator = r1.numerator * r2.numerator;
int new_denominator = r1.denominator * r2.denominator;
simplify(&new_numerator, &new_denominator);
return (Rational) {new_numerator, new_denominator};
}
// 除法
Rational divide(Rational r1, Rational r2) {
if (r2.denominator == 0)
return NULL; // 防止除以零
int new_numerator = r1.numerator * r2.denominator;
int new_denominator = r1.denominator;
simplify(&new_numerator, &new_denominator);
return (Rational) {new_numerator, new_denominator};
}
```
阅读全文