有理数四则运算c语言实现两个有理数相加、相减、相乘的运算。
时间: 2024-09-26 09:08:25 浏览: 38
用C语言实现矩阵运算.doc
在C语言中,我们可以使用结构体来表示有理数,包含分子(numerator)和分母(denominator),然后分别实现加法、减法和乘法操作。以下是简单的有理数四则运算的C语言实现:
```c
#include <stdio.h>
// 定义有理数结构体
typedef struct {
int numerator;
int denominator;
} Rational;
// 计算两个有理数的最大公约数
int gcd(int a, int b) {
if (b == 0)
return a;
return gcd(b, a % b);
}
// 简化有理数(去除最大公约数)
void simplify(Rational* num) {
int gcd_val = gcd(num->numerator, num->denominator);
num->numerator /= gcd_val;
num->denominator /= gcd_val;
}
// 加法
Rational add(Rational a, Rational b) {
Rational result;
result.numerator = a.numerator * b.denominator + a.denominator * b.numerator;
result.denominator = a.denominator * b.denominator;
simplify(&result);
return result;
}
// 减法
Rational subtract(Rational a, Rational b) {
Rational result;
result.numerator = a.numerator * b.denominator - a.denominator * b.numerator;
result.denominator = a.denominator * b.denominator;
simplify(&result);
return result;
}
// 乘法
Rational multiply(Rational a, Rational b) {
Rational result;
result.numerator = a.numerator * b.numerator;
result.denominator = a.denominator * b.denominator;
simplify(&result);
return result;
}
int main() {
Rational a = {5, 7}, b = {3, 4};
printf("a + b = (%d/%d)\n", add(a, b).numerator, add(a, b).denominator);
printf("a - b = (%d/%d)\n", subtract(a, b).numerator, subtract(a, b).denominator);
printf("a * b = (%d/%d)\n", multiply(a, b).numerator, multiply(a, b).denominator);
return 0;
}
```
在这个示例中,我们首先定义了有理数结构,并实现了计算最大公约数、简化有理数以及四个基本运算。在`main`函数中,展示了如何使用这些函数来进行实际的加、减、乘操作。
阅读全文