您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

iOS 開發練習:把四則運算拆成獨立方法的計算器

編輯:iOS 開發綜合

這個練習在練什麼

看似簡單的計算器,重點其實是「職責分離」:把加減乘除四個運算各自獨立成 C 函式,主程式只負責解析輸入並分派。這樣的結構日後要擴充成科學計算機、要加單元測試,都輕鬆得多。

步驟一:宣告對外介面

用 extern 把四個函式的簽名公開出來,實作放在另一個檔案裡。

 extern double add(double x, double y);
extern double subtract(double x, double y);
extern double multiply(double x, double y);
extern double divide(double x, double y);

步驟二:實作運算函式

 #include "MathOperation.h"

double add(double x, double y)      { return x + y; }
double subtract(double x, double y) { return x - y; }
double multiply(double x, double y) { return x * y; }
double divide(double x, double y)   { return x / y; }

步驟三:主程式解析輸入

先把整個式子依空白切成 token 陣列,再逐一判斷每個 token 是運算子還是數字,遇到運算子就更新狀態,遇到數字就依目前運算子做運算。

 BOOL isAnOperator(const char value) {
    return ((value == '+') || (value == '-') || (value == '*') || (value == '/'));
}

int main(int argc, const char * argv[]) {
    double result = 0;
    char operator = '';

    NSString *equation = [NSString stringWithUTF8String:argv[0]];
    NSArray *eqParts = [equation componentsSeparatedByCharactersInSet:
                        [NSCharacterSet whitespaceCharacterSet]];

    for (int n = 0; n < [eqParts count]; n++) {
        NSString *argString = [eqParts objectAtIndex:n];
        char firstChar = [argString characterAtIndex:0];

        if (isAnOperator(firstChar)) {
            operator = firstChar;
            continue;
        }

        double newValue = [argString doubleValue];
        switch (operator) {
            case '+': result = add(result, newValue);      break;
            case '-': result = subtract(result, newValue); break;
            case '*': result = multiply(result, newValue); break;
            case '/': result = divide(result, newValue);   break;
            default: break;
        }
    }
    NSLog(@"%.3f", result);
    return 0;
}

這份程式碼的兩個已知限制

第一,它採用的是「由左至右依序計算」,實作的是計算機式的即時運算邏輯,而不是數學的運算子優先次序。輸入「2 + 3 * 4」會得到 20 而非 14。若要正確處理優先級,需要引入運算子堆疊與運算元堆疊(也就是 shunting-yard 演算法)。

第二,除法沒有做除零檢查。divide 回傳 inf 或 nan 時,後續顯示會變成亂碼,實務上應在函式內判斷 y 是否為 0 並回傳錯誤狀態。

這兩個限制正好是很好的練習延伸題:試著改寫成支援括號與優先順序的版本,你會對資料結構的應用有更深的體會。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved