為整數定義一個抽象數據類型(ADT),封裝常見運算(加減乘除、比較、輸入輸出等),每個運算對應一個函數,通過參數列表與返回值定義接口契約。
// 整數 ADT 接口定義 (int_adt.h)
#ifndef INT_ADT_H
#define INT_ADT_H
typedef struct IntADT* IntHandle; // 不透明指針,隱藏實現細節
// 構造/銷毀
IntHandle int_create(long value); // 由長整數創建
IntHandle int_create_from_str(const char* str); // 由字符串創建(支持大整數)
void int_destroy(IntHandle handle); // 釋放資源
// 基本運算
IntHandle int_add(IntHandle a, IntHandle b); // 加法
IntHandle int_sub(IntHandle a, IntHandle b); // 減法
IntHandle int_mul(IntHandle a, IntHandle b); // 乘法
IntHandle int_div(IntHandle a, IntHandle b); // 除法(商)
IntHandle int_mod(IntHandle a, IntHandle b); // 取模(餘數)
// 比較運算:返回 -1(ab)
int int_cmp(IntHandle a, IntHandle b);
// 輸入輸出
void int_print(IntHandle handle); // 打印到 stdout
char* int_to_string(IntHandle handle); // 返回動態分配的字符串,調用者需 free
// 狀態查詢
int int_is_zero(IntHandle handle);
int int_is_negative(IntHandle handle);
#endif
為突破 long 範圍,內部採用 十進制數組/鏈表存儲每一位,實現任意精度運算。核心結構:
// 內部實現 (int_adt.c)
#define BASE 1000000000 // 10^9,每個元素存 9 位十進制數
#define MAX_DIGITS 1000 // 最大支持位數
struct IntADT {
int digits[MAX_DIGITS]; // 低位在前
int length; // 有效元素個數
int sign; // 1: 正, -1: 負, 0: 零
};
malloc,調用者負責 int_destroy 釋放。#include "int_adt.h"
#include
int main() {
IntHandle a = int_create_from_str("12345678901234567890");
IntHandle b = int_create_from_str("98765432109876543210");
IntHandle sum = int_add(a, b);
printf("Sum: "); int_print(sum); putchar('\n');
IntHandle prod = int_mul(a, b);
printf("Product: "); int_print(prod); putchar('\n');
int_destroy(a); int_destroy(b);
int_destroy(sum); int_destroy(prod);
return 0;
}
errno 機制(如除零、溢出、內存不足);itoa/atoi 實現細節可搜索相關技術博客。C 語言通過不透明指針+函數指針/獨立函數實現 ADT 封裝。整數 ADT 的核心難點在於任意精度運算實現,採用分塊十進制數組是經典且工程可行的方案。良好的接口設計應隱藏內部表示,僅暴露語義清晰的操作函數。