用C语言编写有理数四则计算
时间: 2024-09-21 09:03:42 浏览: 80
c语言做的有理数四则运算器
4星 · 用户满意度95%
在C语言中编写有理数(分数)的四则运算,通常需要创建一个结构体来表示分子和分母,并提供相应的函数来执行加、减、乘、除操作。这里是一个简单的示例:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义一个结构体存储有理数
typedef struct {
int numerator; // 分子
int denominator; // 分母
} Rational;
// 检查分母是否为0,避免除以零错误
int safe_division(int a, int b) {
if (b == 0) {
printf("Error: Division by zero is not allowed.\n");
return -1;
}
return a / b;
}
// 有理数四则运算函数
Rational add(Rational a, Rational b) {
int new_numerator = a.numerator * b.denominator + b.numerator * a.denominator;
int new_denominator = a.denominator * b.denominator;
return (Rational){new_numerator, new_denominator};
}
Rational subtract(Rational a, Rational b) {
int new_numerator = a.numerator * b.denominator - b.numerator * a.denominator;
return (Rational){new_numerator, a.denominator};
}
Rational multiply(Rational a, Rational b) {
return (Rational){a.numerator * b.numerator, a.denominator * b.denominator};
}
Rational divide(Rational a, Rational b) {
int result = safe_division(a.numerator, b.numerator);
return (Rational){result, a.denominator * b.denominator};
}
// 主函数演示如何使用
int main() {
Rational num1 = {5, 3}, num2 = {7, 4};
Rational sum = add(num1, num2);
Rational diff = subtract(num1, num2);
Rational prod = multiply(num1, num2);
Rational div = divide(num1, num2);
printf("Addition: (%d/%d) + (%d/%d) = (%d/%d)\n", num1.numerator, num1.denominator, num2.numerator, num2.denominator, sum.numerator, sum.denominator);
printf("Subtraction: (%d/%d) - (%d/%d) = (%d/%d)\n", num1.numerator, num1.denominator, num2.numerator, num2.denominator, diff.numerator, diff.denominator);
printf("Multiplication: (%d/%d) * (%d/%d) = (%d/%d)\n", num1.numerator, num1.denominator, num2.numerator, num2.denominator, prod.numerator, prod.denominator);
printf("Division: (%d/%d) / (%d/%d) = (%d/%d)\n", num1.numerator, num1.denominator, num2.numerator, num2.denominator, div.numerator, div.denominator);
return 0;
}
```
阅读全文