第一题 定义分数(Fraction)类:
1、成员变量:分子、分母
2、方法:
(1)自定义初始化方法(初始分子和分母)
(2)分子的赋值、取值方法
(3)分母的赋值取值方法
(4)打印分数信息
(5)约分
(6)加、减、乘、除运算方法,返回分数对象。
3、mian.m文件中创建分数对象,测试加、减、乘、除。
提示:加减乘除运算有一个Fraction类型的参数(参与加法运算的另外一个分数对象),有一个Fraction类型的返回值(结果)。
main.m<pre name="code" class="objc">#import <Foundation/Foundation.h>
@interface Fraction : NSObject
{
int _son;
int _mother;
}
- (id)initWithSon:(int)son mother:(int)mother;
- (void)setSon:(int)son mother:(int)mother;
- (int)son;
- (int)mother;
- (void)print;
- (void)yf;
- (Fraction *)add:(Fraction *)f;
- (Fraction *)sub:(Fraction *)f;
- (Fraction *)mul:(Fraction *)f;
- (Fraction *)div:(Fraction *)f;
//- (void)addf1:(Fraction *)f1 f2:(Fraction *)f2;
@end
#import "Fraction.h"
@implementation Fraction
- (id)initWithSon:(int)son mother:(int)mother
{
_son = son;
_mother = mother;
return self;
}
- (void)setSon:(int)son mother:(int)mother
{
_son = son;
_mother = mother;
}
- (int)son
{
return _son;
}
- (int)mother
{
return _mother;
}
- (void)print
{
NSLog(@"%d/%d", _son, _mother);
}
- (void)yf
{
int temp;
int a = _son, b = _mother;
while (0 != a % b) {
temp = a % b;
a = b;
b = temp;
}
_son /= b;
_mother /= b;
}
//- (void)addf1:(Fraction *)f1 f2:(Fraction *)f2
//{
// f1->_son = f1->_son * f2->_mother + f1->_mother * f2->_son;
// f1->_mother *= f2->_mother;
//
//
//}
- (Fraction *)add:(Fraction *)f
{
Fraction *f3 = [[Fraction alloc] init];
f3->_son = self->_son * f->_mother + self->_mother * f->_son;
f3->_mother = self->_mother * f->_mother;
return f3;
}
- (Fraction *)sub:(Fraction *)f
{
Fraction *f3 = [[Fraction alloc] init];
f3->_son = self->_son * f->_mother - self->_mother * f->_son;
f3->_mother = self->_mother * f->_mother;
return f3;
}
- (Fraction *)mul:(Fraction *)f
{
Fraction *f3 = [[Fraction alloc] init];
f3->_son = self->_son * f->_son;
f3->_mother = self->_mother * f->_mother;
return f3;
}
- (Fraction *)div:(Fraction *)f
{
Fraction *f3 = [[Fraction alloc] init];
f3->_son = self->_son * f->_mother;
f3->_mother = self->_mother * f->_son;
return f3;
}
@end
#import <Foundation/Foundation.h>
#import "Fraction.h"
int main(int argc, const char * argv[])
{
@autoreleasepool {
Fraction *f1 = [[Fraction alloc] initWithSon:7 mother:14];
Fraction *f2 = [[Fraction alloc] initWithSon:6 mother:18];
Fraction *result = [f1 add: f2];
[result yf];
[result print];
result = [f1 sub: f2];
[result yf];
[result print];
result = [f1 mul: f2];
[result yf];
[result print];
result = [f1 div: f2];
[result yf];
[result print];
}
return 0;
}