问题
我正在尝试将小数转换为混合分数。我已经设法让我的小应用程序以时尚的方式工作。
这就是我想要做的事情:
我知道(相反,我希望我错过了一些简单的事情),但我只是让自己完全糊涂了。
代码
- (int)gcdForNumber1:(int) m andNumber2:(int) n
{
while( n!= 0) // execute loop until m == n
{
int temp = n; n = m % temp; m = temp;
}
return (m);
}
- (int)tenRaisedTopower:(int)decimalLength
{
int answer = 10;
while (decimalLength!= 1) {
answer *= 10;
decimalLength -- ;
}
return answer;
}
- (void)floatToFraction:(float)decimalNumber
{
NSString *decimalString = [NSString stringWithFormat:@"%f", decimalNumber];
NSArray *components = [decimalString componentsSeparatedByString:@"."];
int decimalLength = [[components objectAtIndex:1] length];
int n = [self tenRaisedTopower:decimalLength];
int m = [[components objectAtIndex:1] intValue];
int gcd = [self gcdForNumber1:m andNumber2:n];
int numer = m/gcd;
int deno = n/gcd;
int fractionnumer = ([[components objectAtIndex:0] intValue] * deno) + numer;
NSString *fractionvalue = [[NSString alloc] initWithFormat:@"%d/%d", fractionnumer, deno ];
self.metersFractionalOutput.text = fractionvalue;
}
感谢Martin R的反馈,你的指针帮助我启动了数学过程,所以我确信可能有更有效的方法来做到这一点,但我通过以下方式解决了这个问题
- (int)gcdForNumber1:(int) m andNumber2:(int) n
{
while( n!= 0) // execute loop until m == n
{
int temp = n; n = m % temp; m = temp;
}
return (m);
}
- (int)tenRaisedTopower:(int)decimalLength
{
int answer = 10;
while (decimalLength!= 1) {
answer *= 10;
decimalLength -- ;
}
return answer;
}
- (void)floatToFraction:(float)decimalNumber
{
NSString *decimalString = [NSString stringWithFormat:@"%f", decimalNumber];
NSArray *components = [decimalString componentsSeparatedByString:@"."];
int decimalLength = [[components objectAtIndex:1] length];
int n = [self tenRaisedTopower:decimalLength];
int m = [[components objectAtIndex:1] intValue];
int gcd = [self gcdForNumber1:m andNumber2:n];
int numer = m/gcd;
int deno = n/gcd;
self.wh = [[components objectAtIndex:0] intValue];
if (numer > deno)
{
int extra = numer / deno;
numer -= extra * deno;
}
NSString *fractionvalue = [[NSString alloc] initWithFormat:@"%d ""%d/%d", self.wh, numer, deno ];
self.metersFractionalOutput.text = fractionvalue;