C语言生成用三元组设计一个可进行有理数四则运算的演示程序
时间: 2024-09-25 08:17:27 浏览: 58
在C语言中,我们可以使用结构体来表示一个三元组(通常称为元组),用于存储有理数的分子、分母以及运算结果。首先,我们需要定义一个名为`RationalNumber`的结构体,然后创建函数来进行加减乘除的运算。
```c
#include <stdio.h>
#include <stdlib.h>
// 定义三元组结构体,表示有理数
typedef struct {
int numerator; // 分子
int denominator; // 分母
} Rational;
// 计算两个有理数的加法
Rational add(Rational a, Rational b) {
int common = __gcd(a.denominator, b.denominator); // 获取最大公约数
return (Rational) {a.numerator * common / b.denominator + b.numerator * common / a.denominator, common};
}
// 减法操作类似
Rational subtract(Rational a, Rational b) {
int common = __gcd(a.denominator, b.denominator);
return (Rational) {a.numerator * common / b.denominator - b.numerator * common / a.denominator, common};
}
// 乘法操作
Rational multiply(Rational a, Rational b) {
return (Rational) {a.numerator * b.numerator, a.denominator * b.denominator};
}
// 除法操作
Rational divide(Rational a, Rational b) {
if (b.denominator == 0) {
printf("Error: Division by zero is not allowed.\n");
return (Rational){0, 0};
}
return (Rational) {a.numerator * b.denominator, a.denominator * b.numerator};
}
// 辅助函数计算最大公约数
int __gcd(int a, int b) {
return b == 0 ? a : __gcd(b, a % b);
}
// 主函数演示
int main() {
Rational num1 = {10, 4}, num2 = {5, 2};
printf("Adding: (%d/%d) + (%d/%d) = (%d/%d)\n", num1.numerator, num1.denominator, num2.numerator, num2.denominator, add(num1, num2).numerator, add(num1, num2).denominator);
printf("Subtracting: (%d/%d) - (%d/%d) = (%d/%d)\n", num1.numerator, num1.denominator, num2.numerator, num2.denominator, subtract(num1, num2).numerator, subtract(num1, num2).denominator);
printf("Multiplying: (%d/%d) * (%d/%d) = (%d/%d)\n", num1.numerator, num1.denominator, num2.numerator, num2.denominator, multiply(num1, num2).numerator, multiply(num1, num2).denominator);
Rational result = divide(num1, num2);
printf("Dividing: (%d/%d) / (%d/%d) = (%d/%d)\n", num1.numerator, num1.denominator, num2.numerator, num2.denominator, result.numerator, result.denominator);
return 0;
}
阅读全文