设计一个c++分数类,要求分数类中包含的分数运算有:两个分数的加减乘除运算,分数的输出格式是:“分子\分母”
时间: 2024-06-06 22:06:41 浏览: 97
大数加减乘除c++类
4星 · 用户满意度95%
#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);
}
Fraction reduction(Fraction frac) // 约分函数
{
if(frac.numerator == 0)
{
frac.denominator = 1;
}
else
{
int divisor = gcd(frac.numerator, frac.denominator);
frac.numerator /= divisor;
frac.denominator /= divisor;
}
return frac;
}
Fraction add(Fraction a, Fraction b) // 加法
{
Fraction result;
result.numerator = a.numerator * b.denominator + a.denominator * b.numerator;
result.denominator = a.denominator * b.denominator;
return reduction(result);
}
Fraction sub(Fraction a, Fraction b) // 减法
{
Fraction result;
result.numerator = a.numerator * b.denominator - a.denominator * b.numerator;
result.denominator = a.denominator * b.denominator;
return reduction(result);
}
Fraction mul(Fraction a, Fraction b) // 乘法
{
Fraction result;
result.numerator = a.numerator * b.numerator;
result.denominator = a.denominator * b.denominator;
return reduction(result);
}
Fraction div(Fraction a, Fraction b) // 除法
{
Fraction result;
result.numerator = a.numerator * b.denominator;
result.denominator = a.denominator * b.numerator;
return reduction(result);
}
void print(Fraction frac) // 输出
{
printf("%d\\%d\n", frac.numerator, frac.denominator);
}
int main()
{
Fraction a = {3, 4};
Fraction b = {2, 5};
print(add(a, b)); // 输出:23\20
print(sub(a, b)); // 输出:7\20
print(mul(a, b)); // 输出:3\10
print(div(a, b)); // 输出:15\8
return 0;
}
阅读全文