2017-06-21 55 views
-3

在c編程中,當我除以2/4這樣的2個數字時,它給出0.5的輸出,但是我想要1/2。所以我想知道如何進行分工來得到像分子/分母這樣的分數的答案。我想用C語言編寫。減少C中的分數

+3

都能跟得上。在C中,'2/4'給出'0'而不是'0.5'。至於這個問題,你如何簡化紙上的分數?你需要找到一個公約數,然後用它除分子和分母,直到不存在這樣的除數(除了1) –

+1

谷歌的'整數除法'。 –

+1

找到HCF,將兩個數字分開並以該格式打印。 – ameyCU

回答

0

你真正想要的是降低分數 ..不計算師。

這裏有一個快速的樣品,這將產生降低分數:

#include <stdbool.h> 
#include <stdio.h> 

//gcf function - return gcd of two numbers 
int gcd(int n, int m) 
{ 
    int gcd, remainder; 

    while (n != 0) 
    { 
     remainder = m % n; 
     m = n; 
     n = remainder; 
    } 

    gcd = m; 

    return gcd; 
}//end gcd function 

int main (int argc, const char * argv[]) { 
    // insert code here... 
    //--declarations 
    int number1, number2; 
    int newNumber1, newNumber2; 

    //--get user input 
    printf("Enter a fraction: "); 
    scanf("%d/%d", &number1, &number2); 

    //--calculations 
    //find the gcd of numerator and denominator 
    //then divide both the numerator and denominator by the GCD 
    newNumber1 = number1/gcd(number1, number2); 
    newNumber2 = number2/gcd(number1, number2); 

    //--results 
    printf("In lowest terms: %d/%d", newNumber1, newNumber2); 
} 

樣品取自:http://snipplr.com/view/42917/

0

C沒有內置此功能。但是,你可以做的是,寫一個小函數,取小數(在你的情況下爲0.5),並返回你正在尋找的表單的分數(即1/2)。

但記得,1/2不是數字;它是一個字符串(char數組)。所以,你只能用它來顯示/打印目的;你不能在算術表達式中使用。

0

抱歉,我不能把這適應C,但可以肯定的港口後勤的代碼,因爲沒有洙複雜

#include <iostream> 
#include <string> 

long GreatestCommonMultiple(long& a, long& b); 
std::string SimplifyThis(long& a, long& b); 

int main(int argC, char** argV) 
{ 
    long n1 = 3; 
    long n2 = 21; 
    std::cout << "This as simplified fraction: " << n1 << "/" << n2 << " is "<<SimplifyThis(n1, n2)<<std::endl; 
    return 0; 
} 

std::string SimplifyThis(long& a, long& b) { 
    long gcm1 = GreatestCommonMultiple(a, b); 
    return std::to_string(a/gcm1) + "/" + std::to_string(b/gcm1); 
} 

long GreatestCommonMultiple(long& a, long& b) { 
    if (b==0) 
    { 
     return a; 
    } 
    long x = (a % b); 
    return GreatestCommonMultiple(b, x); 
}