2012-03-05 62 views
0

我正在一個項目上工作,我對如何開始有一個想法。基本上,這是程序的運行方式:撕掉一個分數

$ ./rulerbuddy 2.25 
2.25 is exactly 2 1/4 

所以,我種有我需要先撕掉整數在這種情況下是「2」的想法,然後開始操縱分數來獲得結果。我的問題是如何從小數部分撕掉整個數字?任何想法,步驟,指導表示讚賞。謝謝。

+0

'floor'向下取整爲最接近的整數,這應該讓你開始。 – pezcode 2012-03-05 23:52:21

回答

4
  1. 取出整數,並考慮只有小數部分(做一個sscanf(input, "%d.%d", &intPart, &fracPart)到t讓他們分開)。

  2. 計算小數點後的位數;你的起始分數是位數/ 10 ^位數,即在你的情況下是25/100;

  3. 現在,您可以簡化它,找到最大公約數(例如Euclid algorithm)並將其除以兩項。這如何可以實現

簡單的例子:

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

struct Fraction 
{ 
    int n; 
    unsigned int d; 
}; 

int gcd(int a, int b) 
{ 
    if(b==0) 
     return a; 
    else 
     return gcd(b, a-b*(a/b)); 
} 

void simplify(struct Fraction * f) 
{ 
    int divisor=gcd(f->n, f->d); 
    f->n/=divisor; 
    f->d/=divisor; 
} 

int main(int argc, char * argv[]) 
{ 
    int intPart; 
    unsigned int fracPart; 
    struct Fraction f; 
    if(argc<2) 
    { 
     puts("Not enough arguments."); 
     return 1; 
    } 
    if(sscanf(argv[1], "%d.%u", &intPart, &fracPart)!=2) 
    { 
     puts("Invalid input."); 
     return 2; 
    } 
    f.n=fracPart; 
    f.d=fracPart!=0?(int)pow(10., floor(log10(fracPart)+1)):1; 
    simplify(&f); 
    printf("%s is exactly: %d %d/%u\n", argv[1], intPart, f.n, f.d); 
    return 0; 
} 
+0

這個程序如何實現的好例子。非常感謝Matteo Italia先生 – 2012-03-06 00:48:32

1

嘗試正則表達式

http://rubular.com/r/KkE34B4ODQ

我有設定爲您的工作,例如,你可能需要根據你的程序提供什麼整數(改變它ie.e 2 0/1)或其他。

,第一組爲整個 二是分子 三是分母

+0

我不會在C程序中使用正則表達式(=依賴於外部庫),其中普通的'sscanf'就足夠了。 – 2012-03-06 00:11:31

+0

很高興知道這一點,感謝您的幫助。 – 2012-03-06 00:50:20

2
if(num < 0) 
    num = num * (-1); 

then 
Just type cast the number explicitly to `int` 
+0

當你有一個負數 – scrappedcola 2012-03-05 23:52:59

+0

啊!我編輯它。 – noMAD 2012-03-05 23:54:16

+0

不一定是錯誤的答案,因爲OP沒有明確說明他是否需要維持負數或只是想要整數。只是想我會指出 – scrappedcola 2012-03-05 23:57:52

2

使用標準庫函數floor

#include <math.h> 

int WholeNumber(double number) 
{ 
    return (int)floor(number); 
} 

int main(void) 
{ 
    int N; 
    N = WholeNumber(2.25); 

    printf("The Whole part is %d\n", N); // this will print 2 
} 
+0

因爲他想把它轉換成精確的分數,所以我不認爲這是一個好主意,因爲他想把它轉換爲精確的分數,並且我懷疑當使用FP值時0.1會給出令人滿意的結果...... – 2012-03-05 23:56:59

+0

非常好,非常感謝你abelenky先生 – 2012-03-06 00:50:04