分數的約分及加減乘除運算

2021-07-03 13:37:38 字數 2544 閱讀 3315

定義⼀個分數類(fraction)

例項變數:分子,分母

⽅法:初始化⽅方法(2個引數),便利構造器,約分,列印,加,減,乘,除。

main.m

#import

#import "fraction.h"

int main(int argc, const char * argv)

fraction.h

#import

@inte***ce fraction : nsobject

//自定義初始化方法

- (id)initwithnumerator:(nsinteger)anumerator;

- (id)initwithnumerator:(nsinteger)anumerator denominator:(nsinteger)adenominator;

//便利構造器

+ (fraction *)fractionwithnumerator:(nsinteger)anumerator denominator:(nsinteger)adenominator;

//setter和getter

- (void)setnumerator:(nsinteger)anumerator;

- (nsinteger)numerator;

- (void)setdenominator:(nsinteger)adenominator;

- (nsinteger)denominator;

//最大公約數:輾轉相除法

- (nsinteger)greatestcommondivisorwit

honenumber:(nsinteger)onenumber anothernumber:(nsinteger)anothernumber;

//約分

- (void)reductionoffraction;

//列印

- (void)print;

//加+ (fraction *)addwitfafraction:(fraction *)afraction bfraction:(fraction *)bfraction;

//減+ (fraction *)minuswitfafraction:(fraction *)afraction bfraction:(fraction *)bfraction;

//乘+ (fraction *)timewitfafraction:(fraction *)afraction bfraction:(fraction *)bfraction;

//除+ (fraction *)dividewitfafraction:(fraction *)afraction bfraction:(fraction *)bfraction;

@end

fraction.m

#import "fraction.h"

@implementation fraction

- (id)init

return self;

}- (id)initwithnumerator:(nsinteger)anumerator

- (id)initwithnumerator:(nsinteger)anumerator denominator:(nsinteger)adenominator

+ (fraction *)fractionwithnumerator:(nsinteger)anumerator denominator:(nsinteger)adenominator

- (void)setnumerator:(nsinteger)anumerator

- (nsinteger)numerator

- (void)setdenominator:(nsinteger)adenominator

- (nsinteger)denominator

//最大公約數:輾轉相除法

- (nsinteger)greatestcommondivisorwithonenumber:(nsinteger)onenumber anothernumber:(nsinteger)anothernumber

return onenumber;

}//約分

- (void)reductionoffraction

//列印

- (void)print

//加+ (fraction *)addwitfafraction:(fraction *)afraction bfraction:(fraction *)bfraction

//減+ (fraction *)minuswitfafraction:(fraction *)afraction bfraction:(fraction *)bfraction

//乘+ (fraction *)timewitfafraction:(fraction *)afraction bfraction:(fraction *)bfraction

//除+ (fraction *)dividewitfafraction:(fraction *)afraction bfraction:(fraction *)bfraction

@end

分數的加減乘除

用分數形式表示的有理數類如下 class rational 求最小公倍數 最小公倍數等於兩數乘積 最大公約數 int mcm int a,int b 定義乙個結構體 存放乙個數的分子與分母 struct rational 化簡 將分數化為最簡 分子分母同除它們的最大公約數 void simplify...

sql的加減乘除運算 mongo 加減乘除運算

mongo語法的四則運算符號 加法 add 減法 subtract 乘法 multiply 除法 divide 求模 mod 以除法為例 其餘同 資料庫course表存在一條 id 為 5ab4dfcabeb21f77cf7dbdf3 的資料,delete欄位為2,total欄位為12,求該條資料的...

大數加減乘除及模運算

自己寫的 測試了幾組測試樣例,都沒什麼問題,如下 define crt secure no deprecate include include include includeusing namespace std const int maxn 3000000 80 const int m 20000...