将小数转换为目标C的分数(有理数)? [英] Convert decimal to fraction (rational number) in Objective C?
问题描述
作为计算器应用程序的一部分,我正在尝试使用sigma表示法实现用途.但是,它输出的结果始终是小数,其余的并不重要.我只是想将小数更改为小数.
As part of a calculator app, I am trying to implement uses with sigma notation. However, the result it prints out is always a decimal, and the rest isn't important. I simply want to change the decimal to a fraction.
我已经具有reduce函数,我遇到的问题是从这样的十进制开始:'0.96875'到其小数值'31/32'
I already have the reduce function, the problem I'm having is getting from a decimal like this: '0.96875' to it's fractional value, '31/32'
谢谢!
PS:我已经调查了几乎所有内容,对于我的一生,我无法弄清楚.此时,我需要的是如何从中取出小数,然后可以将其减少.
PS: I've looked into just about everything, and for the life of me, I can't figure this out. All I need at this point is how to take the decimal out of it, and I can then reduce it.
这是我的reduce方法:
Here is my reduce method:
-(void)reduce {
int u = numerator;
int v = denominator;
int temp;
while (v != 0) {
temp = u % v;
u = v;
v = temp;
}
numerator /= u;
denominator /= u;
}
推荐答案
我自己发现了这个问题.我所做的是将分子和分母乘以1000000(回想小数看起来像.96875/1),这样看起来像96875/100000
.
Found this out myself. What I did was multiply the numerator and denominator by 1000000 (recalling that the decimal looked like .96875/1) so that it looked like 96875/100000
.
然后,我使用此reduce方法将其归为最低术语:
Then, I used this reduce method to bring it into lowest terms:
-(void)reduce {
int u = numerator;
int v = denominator;
int temp;
while (v != 0) {
temp = u % v;
u = v;
v = temp;
}
numerator /= u;
denominator /= u;
}
最后,我使用打印方法将其转换为小数形式:
And finally,I used a print method to get it into fraction form:
//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);
}
}
得到我想要的输出:
31/32
这篇关于将小数转换为目标C的分数(有理数)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!