用C语言写一个计算分数加减乘除的代码
时间: 2023-04-12 21:00:22 浏览: 190
C语言编写的加减乘除运算
好的,以下是用C语言写一个计算分数加减乘除的代码的示例:
```
#include <stdio.h>
typedef struct {
int numerator; // 分子
int denominator; // 分母
} Fraction;
// 求最大公约数
int gcd(int a, int b) {
if (b == 0) {
return a;
} else {
return gcd(b, a % b);
}
}
// 约分
void reduce(Fraction *f) {
int g = gcd(f->numerator, f->denominator);
f->numerator /= g;
f->denominator /= g;
}
// 加法
Fraction add(Fraction f1, Fraction f2) {
Fraction result;
result.numerator = f1.numerator * f2.denominator + f2.numerator * f1.denominator;
result.denominator = f1.denominator * f2.denominator;
reduce(&result);
return result;
}
// 减法
Fraction subtract(Fraction f1, Fraction f2) {
Fraction result;
result.numerator = f1.numerator * f2.denominator - f2.numerator * f1.denominator;
result.denominator = f1.denominator * f2.denominator;
reduce(&result);
return result;
}
// 乘法
Fraction multiply(Fraction f1, Fraction f2) {
Fraction result;
result.numerator = f1.numerator * f2.numerator;
result.denominator = f1.denominator * f2.denominator;
reduce(&result);
return result;
}
// 除法
Fraction divide(Fraction f1, Fraction f2) {
Fraction result;
result.numerator = f1.numerator * f2.denominator;
result.denominator = f1.denominator * f2.numerator;
reduce(&result);
return result;
}
int main() {
Fraction f1 = {2, 3};
Fraction f2 = {3, 4};
Fraction result = add(f1, f2);
printf("%d/%d + %d/%d = %d/%d\n", f1.numerator, f1.denominator, f2.numerator, f2.denominator, result.numerator, result.denominator);
result = subtract(f1, f2);
printf("%d/%d - %d/%d = %d/%d\n", f1.numerator, f1.denominator, f2.numerator, f2.denominator, result.numerator, result.denominator);
result = multiply(f1, f2);
printf("%d/%d * %d/%d = %d/%d\n", f1.numerator, f1.denominator, f2.numerator, f2.denominator, result.numerator, result.denominator);
result = divide(f1, f2);
printf("%d/%d / %d/%d = %d/%d\n", f1.numerator, f1.denominator, f2.numerator, f2.denominator, result.numerator, result.denominator);
return 0;
}
```
希望这个示例能够帮助你理解如何用C语言计算分数的加减乘除。
阅读全文