有理数四则运算c语言实现两个有理数相加、相减、相乘,相除的运算要完整代码
时间: 2024-09-25 07:16:43 浏览: 51
在C语言中,我们可以创建结构体来表示有理数,包括分子和分母,并分别实现加法、减法、乘法和除法的操作。由于C语言本身并不支持直接的浮点数除法得到有理数结果,我们需要手动处理除法的结果。
首先,我们定义一个`Fraction`结构体:
```c
#include <stdio.h>
typedef struct {
int numerator; // 分子
int denominator; // 分母
} Fraction;
// 函数声明
Fraction add(Fraction a, Fraction b);
Fraction subtract(Fraction a, Fraction b);
Fraction multiply(Fraction a, Fraction b);
Fraction divide(Fraction a, Fraction b);
// 主函数示例,用于测试上述函数
int main() {
// 创建并初始化两个有理数
Fraction num1 = {5, 7};
Fraction num2 = {3, 4};
// 打印操作结果
printf("Addition: %d/%d + %d/%d = %d/%d\n", num1.numerator, num1.denominator, num2.numerator, num2.denominator, add(num1, num2).numerator, add(num1, num2).denominator);
printf("Subtraction: %d/%d - %d/%d = %d/%d\n", num1.numerator, num1.denominator, num2.numerator, num2.denominator, subtract(num1, num2).numerator, subtract(num1, num2).denominator);
printf("Multiplication: %d/%d * %d/%d = %d/%d\n", num1.numerator, num1.denominator, num2.numerator, num2.denominator, multiply(num1, num2).numerator, multiply(num1, num2).denominator);
if (num2.denominator != 0) {
printf("Division: %d/%d / %d/%d = %d/%d\n", num1.numerator, num1.denominator, num2.numerator, num2.denominator, divide(num1, num2).numerator, divide(num1, num2).denominator);
} else {
printf("Cannot divide by zero.\n");
}
return 0;
}
// 运算函数的具体实现
Fraction add(Fraction a, Fraction b) {
int commonDen = __gcd(a.denominator, b.denominator); // 获取最大公约数
int newNum = (a.numerator * commonDen + b.numerator * a.denominator) / commonDen;
return (Fraction){newNum, commonDen};
}
Fraction subtract(Fraction a, Fraction b) {
int commonDen = __gcd(a.denominator, b.denominator);
int newNum = (a.numerator * commonDen - b.numerator * a.denominator) / commonDen;
return (Fraction){newNum, commonDen};
}
Fraction multiply(Fraction a, Fraction b) {
return (Fraction){a.numerator * b.numerator, a.denominator * b.denominator};
}
Fraction divide(Fraction a, Fraction b) {
if (b.denominator == 0) {
return (Fraction){0, 0}; // 防止除以零
}
int commonDen = a.denominator * b.denominator;
int newNum = a.numerator * b.denominator;
return (Fraction){newNum, commonDen};
}
```
在这个代码片段中,`__gcd`是一个计算最大公约数的辅助函数,为了保证分数的正确性,我们在除法运算中检查了除数是否为零。请注意,这个代码仅作为演示目的,并未包含错误处理和输入验证,实际项目中需要根据需求添加更多细节。下面是几个相关的函数实现细节:
阅读全文