减少 c 中的分数

reducing a fraction in c

#include <stdio.h>
#include <stdlib.h>
int main(){
    system("color f0");
    int a,b,c,d,e,f,g,h,z;
    printf("First numerator:");
    scanf("%d",&a);
    printf("First denominator:");
    scanf("%d",&b);
    printf("Second numerator:");
    scanf("%d",&c);
    printf("Second denominator:");
    scanf("%d",&d);

    a=a*d;
    c=c*b;
    e=a+c;
    f=b*d;
    printf("Simple form:%d/%d\n",e,f);
    return 0;
}

这是我的代码,我想在不使用数学库的情况下将简单分数减少到尽可能低的水平

堆栈溢出!= /r/homeworkhelp

伪代码算法:

get a fraction in the form of a/b

while a/b is not in lowest terms:
    find a common divisor, k
    divide a by k  
    divide b by k
end while

检查是否是最低条款:

if A == B:
    [not lowest terms]
if A is a multiple of B:
    [not lowest terms]
if there is a common divisor: // this catches the first two.
    [not lowest terms]
else:
    [lowest terms]

我要把除数查找器留给你,否则容易了。

你用你的代码做了一些奇怪的事情:

首先,您要求用户提供两个个提名人和两个个分母。

所以你的台词

printf("Second numerator:");
scanf("%d",&c);
printf("Second denominator:");
scanf("%d",&d);

多余的可以删除。

二、你行

a=a*d;
c=c*b;
e=a+c;
f=b*d;

可怕 - reader(和你)将迷失在你的 1 个字母的名字中。

那么,为什么不为 分母 的变量命名 nominator 而为 分母 的变量命名呢? denominator?等等?

所以用这个替换你的整个代码:

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int numerator, denominator, smaller, i;

    system("color f0");

    printf("Numerator  : ");
    scanf("%d",&numerator);

    printf("Denominator: ");
    scanf("%d",&denominator);

    printf("\nOriginal fraction: %d/%d\n", numerator, denominator);

    // Method: We get the smaller number from numerator and denominator
    // and will try all numbers from it decreasing by 1 for common divisor

    smaller = numerator < denominator ? numerator : denominator;

    for (i = smaller; i > 1; --i)
        if (numerator % i == 0 && denominator % i ==0)
        {
            numerator   /= i;
            denominator /= i;
            break;
        }

    printf("Reduced fraction : %d/%d\n", numerator, denominator);
    return 0;
}