當前位置:編程學習大全網 - 編程語言 - c語言:分數的乘法

c語言:分數的乘法

#包含?& ltstdio.h & gt

#包含?& ltstdlib.h & gt

struct?分數

{

int?分子;?//?分子

int?分母;?//?分母

int?符號;?//?符號,分子為負數時,值為-1,為正數時,值為1,其他值無意義。

};

int?scan_frac(struct?分數?*f,?struct?分數?* g);//?根據題目格式輸入兩個分數,存儲在f和g指示的內存中。

struct?分數?multiply_frac(struct?分數?f,?struct?分數?g);?//返回分數f和g的乘積。

int?主()

{

struct?分數?f1,?f2,?產品;

while(scan _ frac(& amp;f1,?& ampf2)?!=?EOF)

{

產品?=?multiply_frac(f1,?F2);

if(product .分子?==?0)

{

printf(" 0 \ n ");

繼續;

}

if(product.symbol?==?-1)

printf("-");

printf("%d/%d\n ",product .分子,?產品.分母);

}

回歸?0;

}

//讀取

int?scan_frac(struct?分數?*f,?struct?分數?*g)

{

夏爾?c = 0;

int?* tmpnum = & ampf-& gt;分子;

* tmpnum = 0;

f-& gt;symbol = 1;

while((c=getchar())!='\n ')

{

if(c & lt;= ' 9 ' & amp& ampc & gt='0')

?* tmpnum = * tmpnum * 10+c-' 0 ';

不然呢?if(c=='/')

{

tmpnum = & ampf-& gt;分母;

* tmpnum = 0;

}

不然呢?if(c=='-')

f-& gt;symbol =-1;

}

tmpnum = & ampg-& gt;分子;

* tmpnum = 0;

g-& gt;symbol = 1;

while((c=getchar())!='\n ')

{

if(c & lt;= ' 9 ' & amp& ampc & gt='0')

?* tmpnum = * tmpnum * 10+c-' 0 ';

不然呢?if(c=='/')

{

tmpnum = & ampg-& gt;分母;

?* tmpnum = 0;

}

不然呢?if(c=='-')

g-& gt;symbol =-1;

}

fflush(stdin);

回歸?c;

}

//產品

struct?分數?multiply_frac(struct?分數?f,?struct?分數?g)

{

int?I = 0;

int?tmp1,tmp2

struct?分數?*結果=(struct?分數?*)malloc(sizeof(?struct?分數));

//關於積分

tmp 1 = f . denominator * g . denominator;

tmp2=f .分子*g .分子;

I = tmp 1 & gt;tmp2?tmp 2:tmp 1;

while(I & gt;=2)

{

if(tmp1%i==0

& amp& amptmp2%i==0)

{

tmp 1/= I;

tmp 2/= I;

}

?I-;

}

?結果-& gt;分母= tmp 1;

?結果-& gt;分子= tmp2

結果-& gt;symbol=f .分子*g .分子;

回歸?*結果;

}

  • 上一篇:高中生可以學什麽技術?
  • 下一篇:用編程貓編寫我的世界教程
  • copyright 2024編程學習大全網