C语言分数相加求和

Python016

C语言分数相加求和,第1张

#include <stdio.h>

#include <math.h>

int fenzi(int i)  // 分子就是 1 3 7 13 21 31  他们之间的差是 2 4 6 8 10

{

    if (i <= 0)

        return 1

    return i * 2 + fenzi(i-1)

}

int fenmu(int i)  // 分母就是 2 的 i + 1 次方

{

    return (int)pow(2, i+1)

}

int main()

{

    double sum = 0

    int flag, x, y

    for (int i = 0 i < 20 i++)

    {

        x = fenzi(i)

        y = fenmu(i)

        flag = pow(-1, i)  // + - 随i是奇偶变换

        printf("%c%d/%d", flag > 0 ? '+' : '-', x, y)

        sum += flag * x * 1.0 / y

    }

    printf(" = %lf\n", sum)

    return 0

}

//结构定义中包含两个成员,分子和分母

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

}

#include <stdio.h>

#include <math.h>

#include <conio.h>

typedef struct

{

int x /*分子*/

int y /*分母*/

}Frac

void Simplify(Frac* c) /*化简分式:2/4化简为1/2*/

{

if(c->y<0)

{

c->x=-c->x

c->y=-c->y

}

int a=abs(c->x),b=abs(c->y)

while(a!=0&&b!=0) a<b?b-=a:a-=b

int k=((a==0) ? b : a)

c->x=c->x/k

c->y=c->y/k

}

void Add(Frac a,Frac b,Frac*c) /* 分式相加:c=a+b */

{

c->x=(a.x*b.y+a.y*b.x)

c->y=a.y*b.y

Simplify(c)

}

main()

{

Frac a,b,c,d,sum

printf("请输入三个分数(先输分子,再输分母):\n")

scanf("%d%d",&(a.x),&(a.y))

scanf("%d%d",&(b.x),&(b.y))

scanf("%d%d",&(c.x),&(c.y))

Simplify(&a)

Simplify(&b)

Simplify(&c)

Add(a,c,&d)

Add(d,c,&sum)

printf("%d/%d + %d/%d + %d/%d = %d/%d\n",a.x,a.y,b.x,b.y,c.x,c.y,sum.x,sum.y)

getch()

}