2016-11-15 133 views
-3
#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; 
} 

一小部分这是我的代码,我想简单分数降低到尽可能低的,但没有使用数学库减少在C

+2

请格式化代码。 –

+0

为什么不使用'math.h'?我们不会做功课。 – Blacksilver

+2

@Blacksilver无论如何math.h会在这里帮助? –

回答

1

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

首先,你问提名和分母的用户。

所以你行

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; 
} 
+0

玛丽安你粗鲁,但令人敬畏thnx为你的帮助。 :D –

+0

欢迎你。 – MarianD

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] 

我要离开除数发现者给你,否则它会容易。

+0

我很*很确定这是有效的。如果没有,我会大声吼我,我会解决它。 – Blacksilver

+0

我会回到你身边。希望最好的 –

+0

没问题。我可能会让这个代码成为高尔夫球。 – Blacksilver