如何在此C代码中减少我的分数结果?

时间:2015-11-18 23:22:42

标签: c math

更新1: 在每个人的帮助下,我都能得到: - 我想提出的一点,每个int都需要一个新的定义角色。请看下面的内容,了解答案中的错误以及我的解决方案。

如果有人可以帮助我使这个脚本连续?我的意思是,在完成一个表达式并显示所有解决方案之后,用户应该能够继续并继续使用脚本直到他们想要退出。基本上,我如何循环这整个事情,以便在一次用户输入后不会结束?

 #include<stdio.h>
 #include<math.h>
 #include<string.h>

 int gcd(int a, int b) {
    while(0!=b) { int r = a % b; a=b; b=r; }
    return a;
}
 int input(char* prompt) {
    int res;
    printf("%s: ", prompt);
    scanf("%d", &res);
    return res;
}
 main()
 {
    int add,sub,mul,dd;
    int add1,sub1,mul1,dd1;
    int a,b,c,d;
    a=input("Please enter the numerator for your first equation");
    b=input("Please enter the denominator for your first equation");
    c=input("Please enter the numerator for your second equation");
    d=input("Please enter the denominator for your second equation");
    add=(a*d+b*c);
    add1=(b*d);
    int fac = gcd(add, add1);
        add /=fac;
        add1 /=fac;
    printf("\The sum of your fractions is: %d/%d",add,add1);
    sub=(a*d-b*c);
    sub1=(b*d);
    int red = gcd(sub, sub1);
        sub /=red;
        sub1 /=red;
    printf("\nThe difference of your fractions is: %d/%d",sub,sub1);
    mul=(a*c);
    mul1=(b*d);
    int red1 = gcd(mul, mul1);
        mul /=red1;
        mul1 /=red1;
    printf("\nThe product of your fractions is: %d/%d",mul,mul1);
    dd=(a*d);
    dd1=(b*c);
    int red2 = gcd(dd, dd1);
        dd /=red2;
        dd1 /=red2;
    printf("\nThe quotient of your fractions is: %d/%d",dd,dd1);
 }

2 个答案:

答案 0 :(得分:2)

您需要为每个特定情况重新计算您的gcd,然后除以:

    add=(a*d+b*c);
    add1=(b*d);
    int fac = gcd(add, add1);
    add /=fac;
    add1/=fac;
    printf("\The sum of your fractions is: %d/%d",add,add1);
    sub=(a*d-b*c);
    sub1=(b*d);
    fac = gcd(sub,sub1);
    sub /= fac;
    sub1 /= fac;

答案 1 :(得分:0)

简化分数:

void simp(int *num, int *den)
{
    int i;

    int lim = (*num < *den) ? *num : *den;
    for (i = 2; i < lim; ++i)
        if (*num % i == 0 && *den % i == 0) {
            *num /= i;
            *den /= i;
        }
}