减少C中的分数

enxuqcxy  于 2023-03-07  发布在  其他
关注(0)|答案(2)|浏览(126)
#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;
}
  • 这是我的代码,我想减少,简单的分数,以尽可能低,但不使用数学库 *
v64noz0r

v64noz0r1#

你的代码做了一些奇怪的事情:
首先,您要求用户输入两个名元素和两个分母。
所以你的台词

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

是多余的,您可以删除它们。
第二,你的台词

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

是 * 可怕的 * -读者(和你)将迷失在你的数量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;
}
rxztt3cl

rxztt3cl2#

堆栈溢出!= /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]

我打算把除数查找器留给你,否则它会太容易了。

相关问题