在Objective C中将十进制转换为分数(有理数)?

JTA*_*pps 1 math objective-c rational-numbers

作为计算器应用程序的一部分,我正在尝试使用sigma表示法.但是,它输出的结果总是小数,其余的并不重要.我只想将小数更改为分数.

我已经有了reduce函数,我遇到的问题是从这样的小数点开始:'0.96875'到它的小数值,'31/32'

谢谢!

PS:我已经调查了几乎所有事情,而对于我的生活,我无法弄清楚这一点.此时我需要的是如何从中取出小数,然后我可以减少它.

这是我的reduce方法:

    -(void)reduce {

    int u = numerator;
    int v = denominator;
    int temp;

    while (v != 0) {
        temp = u % v;
        u = v;
        v = temp;
    }

    numerator /= u;
    denominator /= u;

}
Run Code Online (Sandbox Code Playgroud)

JTA*_*pps 5

我自己发现了这个.我所做的是将分子和分母乘以1000000(回想小数看起来像.96875/1),这样看起来就像96875/100000.

然后,我使用此reduce方法将其置于最低项:

    -(void)reduce {

    int u = numerator;
    int v = denominator;
    int temp;

    while (v != 0) {
        temp = u % v;
        u = v;
        v = temp;
    }

    numerator /= u;
    denominator /= u;

}
Run Code Online (Sandbox Code Playgroud)

最后,我使用print方法将其转换为分数形式:

//In the .h
@property int numerator, denominator, mixed;
-(void)print;

//In the .m       
@synthesize numerator, denominator, mixed;

-(void)print {
    if (numerator > denominator) {
        //Turn fraction into mixed number
        mixed = numerator/denominator;
        numerator -= (mixed * denominator);
        NSLog(@"= %i %i/%i", mixed, numerator, denominator);
    } else if (denominator != 1) {
        //Print fraction normally
        NSLog(@"= %i/%i", numerator, denominator);
    } else {
        //Print as integer if it has a denominator of 1
        NSLog(@"= %i", numerator);
    }
}
Run Code Online (Sandbox Code Playgroud)

得到了我想要的输出:

31/32
Run Code Online (Sandbox Code Playgroud)