C++实现折半查找算法及银行账户管理系统

本文将介绍两个使用 C++ 编写的程序:

  1. 实现有序表的折半查找算法2. 设计一个 Bank 类,用于管理银行账户的资金往来账目

一、有序表的折半查找算法

以下是使用 C++ 语言编写的实现有序表的折半查找算法的代码:cpp#include using namespace std;

int binarySearch(int arr[], int left, int right, int target) { while (left <= right) { int mid = left + (right - left) / 2; if (arr[mid] == target) { return mid; } else if (arr[mid] < target) { left = mid + 1; } else { right = mid - 1; } } return -1;}

int main() { int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9}; int target = 6; int size = sizeof(arr) / sizeof(arr[0]); int result = binarySearch(arr, 0, size - 1, target); if (result == -1) { cout << 'Target not found' << endl; } else { cout << 'Target found at index ' << result << endl; } return 0;}

代码解释:

这段代码定义了一个 binarySearch 函数,该函数接受一个有序数组 arr、查找范围的左边界 left、右边界 right 以及目标值 target 作为参数。

函数内部使用循环实现折半查找:

  • 每次循环计算中间位置 mid;* 如果 arr[mid] 等于目标值,则返回 mid,表示找到目标值;* 如果 arr[mid] 小于目标值,则将左边界更新为 mid + 1;* 如果 arr[mid] 大于目标值,则将右边界更新为 mid - 1

如果循环结束后仍未找到目标值,则返回 -1。

二、Bank 类实现银行账户管理

以下是 Bank 类的实现:cpp#include #include #include using namespace std;

class Bank {private: string accountNumber; time_t creationDate; double balance; vector<pair<time_t, double>> transactionHistory;

public: Bank(string accountNumber, double initialBalance) { this->accountNumber = accountNumber; this->creationDate = time(0); this->balance = initialBalance; }

void deposit(double amount) {        balance += amount;        transactionHistory.push_back(make_pair(time(0), amount));    }

void withdraw(double amount) {        if (balance >= amount) {            balance -= amount;            transactionHistory.push_back(make_pair(time(0), -amount));        } else {            cout << 'Insufficient balance' << endl;        }    }

void printTransactionHistory() {        time_t currentTime = time(0);        for (int i = transactionHistory.size() - 1; i >= 0; i--) {            if (currentTime - transactionHistory[i].first <= 30 * 24 * 60 * 60) {                cout << 'Date: ' << ctime(&transactionHistory[i].first);                cout << 'Amount: ' << transactionHistory[i].second << endl;            }        }    }};

int main() { Bank bank('1234567890', 1000); bank.deposit(500); bank.withdraw(200); bank.printTransactionHistory(); return 0;}

代码解释:

  • Bank 类包含账户号码 accountNumber、创建日期 creationDate、余额 balance 和交易记录 transactionHistory。* deposit 方法用于存款,withdraw 方法用于取款,这两个方法都会更新余额并记录交易历史。* printTransactionHistory 方法用于打印最近一个月的交易记录。

总结:

本文介绍了使用 C++ 实现折半查找算法和银行账户管理系统。折半查找算法是一种高效的查找算法,适用于有序数组。Bank 类提供了一种方便的方式来管理银行账户,包括存款、取款和查询交易记录等功能。

C++实现折半查找算法及银行账户管理系统

原文地址: https://www.cveoy.top/t/topic/f3Zo 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录