题:改变第七章例子中print方法,增加bool参数,判断如果是YES则对分数进行约简
@interface Fraction : NSObject
{
//int num,den; }
@property int num,den;//定义属性 - (void) print:(BOOL) yesOrNo;//打印并判断是否约简分数
//- (void) setN: (int) n;//设置n的值
//- (void) setD: (int) d;//设置d的值
//- (int) n;//返回n的值
//- (int) d;//返回d的值
- (void) setN: (int) n andSetD: (int) d;//2个参数的方法分别设置n和d的值
- (double) convertToNum;
- (void) add: (Fraction *) f;//分数相加方法
- (void) reduce;//分数约简方法
- (Fraction *) addFraction: (Fraction *) f;//加
- (Fraction *) subFraction: (Fraction *) f;//减
- (Fraction *) mulFraction: (Fraction *) f;//乘
- (Fraction *) divFraction: (Fraction *) f;//除
@end #import "Fraction.h" @implementation Fraction @synthesize num,den;//属性对应@property num,den - (void) print: (BOOL) yesOrNo//打印
{
if (yesOrNo == YES) {
[self reduce];
}
NSLog(@"%i/%i",num,den);
}
//- (void) setN: (int) n//设置n的值
//{
// num = n;
//}
//- (void) setD: (int) d//设置d的值
//{
// den = d;
//}
//- (int) n//返回n的值
//{
// return num;
//}
//- (int) d//返回d的值
//{
// return den;
//} - (void) setN: (int) n andSetD: (int) d
{
num = n;
den = d; }
- (double) convertToNum
{
if (den != )
{
return (double) num/den; }
else
{
return NAN; }
} - (void) add: (Fraction *) f
{
//分数相加:a/b + c/d = ((a*d) + (b*c)) / (b*d) num = num * f.den + den * f.num;
den = den * f.den; [self reduce];
} - (void) reduce
{
int u = num;
int v = den;
int temp; while (v != )
{
temp = u % v;
u = v;
v = temp; }
num /= u;
den /= u;
} //加法
- (Fraction *) addFraction: (Fraction *) f
{
Fraction *result = [[Fraction alloc]init]; result.num = num * f.den + den * f.num; result.den = den * f.den; [result reduce]; return result; } //减法
- (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; } //乘法
- (Fraction *) mulFraction: (Fraction *) f
{
Fraction *result = [[Fraction alloc]init]; result.num = num * f.num;
result.den = den * f.den; [result reduce]; return result;
} //除法
- (Fraction *) divFraction: (Fraction *) f
{
//计算分数除以分数,第一个分数乘以第二个分数的倒数:1/2除以3/2 = 1/2 * 2/3
Fraction *result = [[Fraction alloc]init]; result.num = num * f.den;
result.den = den * f.num; //[result reduce]; return result;
}
@end #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; [myF setN: andSetD:];
[myF_2 setN: andSetD:]; myResult = [myF subFraction:myF_2];
//[myResult print]; myResult = [myF mulFraction:myF_2];
//[myResult print]; myResult = [myF divFraction:myF_2]; int i;//定义整型变量i记录输入值
BOOL b;//定义BOOL类型通过i值传递判断yes or no
NSLog(@"Need to Simple? 1 or 0");
//NSLog(@"ifReadOnly value: %@" ,ifReadOnly?@"YES":@"NO");
scanf("%i",&i);
b = i;//将i值赋给b
[myResult print:b]; }
return ;
}