C语言 定义一个表示分数的结构体,并求两个分数相加之和

RT。

第1个回答  2018-04-11
#include<cstdio>
#include<iostream>
using namespace std;
struct Myfloat {
    int son,mother;
    Myfloat(int x=0,int y=0) {
        son=y;
        mother=x;
    }
    void pt() {
        printf("%d/%d",son,mother);
    }
};
int gcd(int x, int y) {
    int z = y;
    while(x%y!=0) {
        z = x%y;
        x = y;
        y = z;
    }
    return z;
}
int lcm(int x, int y){
    return x*y/gcd(x,y);
}
Myfloat operator + (Myfloat F1,Myfloat F2) {
    int bigmother=lcm(F1.mother,F2.mother);
    int bigson=F1.son*bigmother/F1.mother+F2.son*bigmother/F2.mother;
    int biggcd=gcd(bigson,bigmother);
    return Myfloat(bigmother/biggcd,bigson/biggcd);
}
int main() {
    //try:
    Myfloat a(5,4); // 4/5
    Myfloat b(6,7); // 7/6
    Myfloat c=a+b;
    c.pt();// 59/30
    return 0;
}

利用最大公约数和最小公倍数进行计算

第2个回答  2018-02-01
顺便说明一下,由于我用的是win-Tc编译器,getch()只是接受一个字符起暂停一下的作用,
以便能看到输出结果
#include
#include

typedef struct
{
int fenZi;
int fenMu;
}fenShu;

fenShu convert(fenShu tmp)
{
int i,sttmp,sttmp2;
sttmp=(tmp.fenZi>tmp.fenMu)? tmp.fenZi:tmp.fenMu;
sttmp2=(tmp.fenZi>tmp.fenMu)? tmp.fenMu:tmp.fenZi;
sttmp=sqrt(sttmp);
for(i=2;i<=sttmp&&i<=sttmp2;i++)
{
if(tmp.fenZi%i==0&&tmp.fenMu%i==0)
{
tmp.fenZi/=i;
tmp.fenMu/=i;
i--;
}
}
return tmp;

}

fenShu add(fenShu a,fenShu b)
{
fenShu tmp;
tmp.fenMu=a.fenMu*b.fenMu;
tmp.fenZi=a.fenZi*b.fenMu+a.fenMu*b.fenZi;
return convert(tmp);
}

void main()
{
fenShu num1,num2,tmpnum;
int tmp;
printf("\t\tBetween fenShu and fenMu is / \n\n");
do{
printf("Please input the first fenShu num1:");
scanf("%d/%d",&num1.fenZi,&num1.fenMu);
}while(num1.fenMu==0);
do{
printf("Please input the second fenShu num2:");
scanf("%d/%d",&num2.fenZi,&num2.fenMu);
}while(num2.fenMu==0);
tmpnum=add(num1,num2);
printf("\n\tThe answer is :\t");
printf("%d/%d",tmpnum.fenZi,tmpnum.fenMu);
getch();
}
第3个回答  2010-12-29
//结构定义中包含两个成员,分子和分母
struct fraction
{
int up, down;/*分子和分母*/
};

/*
相加算法的核心是找两个分母的最小公倍数和结果分子分母的最大公约数,分别单独函数来求
*/
int pubtime(int, int);//最小公倍数
int pubsub(int, int);//最大公约数,可用辗转相除法求,挺经典的一个方法。

/********分数相加********/
fraction add(fraction f1, fraction f2)
{
fraction result;
result.down = pubtime(f1.down, f2.down);
result.up = f1.up * result.down / f1.down + f2.up * result.down / f2.down;
int n = pubsub(result.up, result.down);
result.up /= n; result.down /= n;
return result;
}

int pubtime(int n1, int n2)
{
int n = pubsub(n1, n2);
return n1 * n2 / n;
}
int pubsub(int n1, int n2)
{
int r = n1;
if(n2 > n1)
r = n1, n1 = n2, n2 = r;
do
{ /*辗转相除*/
r = n1 % n2;
if(r == 0) break;
n1 = n2; n2 = r;
}while(true);
return n2;
}