题:Fraction类对负分数适用吗?例如:1/4-1/2 能否显示成-1/4?
//--------类定义实现参考上篇随笔,此处需更改print方法和main主方法部分----------
- (void) print: (BOOL) yesOrNo//打印
{
if (yesOrNo == YES) {
[self reduce];
} if (num < )
{
num = -num;
NSLog(@"-%i/%i",num,den);
}
else
{
NSLog(@"%i/%i",num,den);
}
} - (Fraction *) subFraction: (Fraction *) f
{
Fraction *result = [[Fraction alloc]init]; result.num = num * f.den - den * f.num;
result.den = den * f.den; //[result reduce]; return result; } #import <Foundation/Foundation.h>
#import "Fraction.h" int main(int argc, const char * argv[]) {
@autoreleasepool {
Fraction *myF = [[Fraction alloc]init];
Fraction *myF_2 = [[Fraction alloc]init];
Fraction *myResult; int i;//接受输入1或0
BOOL b;//布尔类型判断i的值 [myF setN: andSetD:];
[myF_2 setN: andSetD:]; NSLog(@"Need to Simple? 1 or 0");//提示输入1或0
scanf("%i",&i);
b = i;//将i值传给布尔类型的b判断是否对分数进行约简 myResult = [myF subFraction:myF_2];//减法
[myResult print:b]; myResult = [myF mulFraction:myF_2];//乘法
//[myResult print]; myResult = [myF divFraction:myF_2];//除法
[myResult print:b]; //[myResult print]; }
return ;
}