C语言生成用三元组设计一个可进行有理数四则运算的演示程序 把加法 減法 除法 和乘法也編譯出來
时间: 2024-10-09 21:01:06 浏览: 27
C语言程序设计 1.7整数乘除法练习器:编写一个练习器,提供给小学生使用,可进行100以内任意两个整数的乘除法练习
为了在C语言中创建一个支持有理数(分数形式)的四则运算演示程序,我们可以使用结构体表示分数(三元组),包含分子(numerator)、分母(denominator)以及一些辅助函数进行加、减、乘、除操作。下面是一个简单的示例:
首先,定义一个分数结构体(fraction):
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct {
int numerator;
int denominator;
} Fraction;
// 初始化分数
Fraction create_fraction(int num, int den) {
Fraction frac;
if (den != 0) {
frac.numerator = num;
frac.denominator = den;
} else {
printf("Error: Division by zero not allowed.\n");
return frac;
}
return frac;
}
// 加法
Fraction add(Fraction a, Fraction b) {
int new_numerator = (a.numerator * b.denominator + b.numerator * a.denominator);
int new_denominator = a.denominator * b.denominator;
return create_fraction(new_numerator, new_denominator);
}
// 减法
Fraction subtract(Fraction a, Fraction b) {
int new_numerator = (a.numerator * b.denominator - b.numerator * a.denominator);
return create_fraction(new_numerator, a.denominator * b.denominator);
}
// 乘法
Fraction multiply(Fraction a, Fraction b) {
int new_numerator = a.numerator * b.numerator;
int new_denominator = a.denominator * b.denominator;
return create_fraction(new_numerator, new_denominator);
}
// 除法,这里处理简化分数
Fraction divide(Fraction a, Fraction b) {
int gcd = __gcd(a.numerator, a.denominator); // 使用欧几里得算法求最大公约数
a.numerator /= gcd;
a.denominator /= gcd;
int result_numerator = a.numerator * b.denominator;
int result_denominator = a.denominator * b.numerator;
return create_fraction(result_numerator, result_denominator);
}
int main() {
Fraction a = create_fraction(4, 5);
Fraction b = create_fraction(2, 7);
Fraction sum = add(a, b);
Fraction diff = subtract(a, b);
Fraction prod = multiply(a, b);
Fraction div = divide(a, b);
printf("加法: %d/%d + %d/%d = %d/%d\n", a.numerator, a.denominator, b.numerator, b.denominator, sum.numerator, sum.denominator);
printf("减法: %d/%d - %d/%d = %d/%d\n", a.numerator, a.denominator, b.numerator, b.denominator, diff.numerator, diff.denominator);
printf("乘法: %d/%d * %d/%d = %d/%d\n", a.numerator, a.denominator, b.numerator, b.denominator, prod.numerator, prod.denominator);
printf("除法: %d/%d / %d/%d = %d/%d\n", a.numerator, a.denominator, b.numerator, b.denominator, div.numerator, div.denominator);
return 0;
}
```
这个程序实现了基本的分数四则运算。注意,实际应用中可能需要更完善的错误处理和输入验证。运行此程序将会显示每个操作的结果。
阅读全文