C++实现有序表折半查找和银行账户管理
C++实现有序表折半查找和银行账户管理
本文介绍使用C++实现两种功能:
- 有序表的折半查找算法:快速查找目标元素。2. 银行账户管理系统:模拟银行账户的基本操作。
1. 有序表的折半查找算法
折半查找,也称二分查找,是一种高效的查找算法,适用于已排序的数据集。
**代码实现:**cpp#include
int binarySearch(int arr[], int n, int target) { int left = 0, right = n - 1; 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, 10}; int n = sizeof(arr) / sizeof(arr[0]); int target = 6; int result = binarySearch(arr, n, target); if (result == -1) { cout << 'Element not found.' << endl; } else { cout << 'Element found at index ' << result << endl; } return 0;}
代码解释:
binarySearch函数接收一个有序数组arr、数组长度n和目标值target作为参数。- 使用两个指针left和right分别指向数组的起始和结束位置。- 在每次循环中,计算中间位置mid,并比较arr[mid]与target的大小: - 若相等,则返回mid,表示找到目标值。 - 若arr[mid]小于target,则将left指针移动到mid + 1,继续在右侧子数组中查找。 - 若arr[mid]大于target,则将right指针移动到mid - 1,继续在左侧子数组中查找。- 若循环结束仍未找到目标值,则返回 -1,表示数组中不存在该元素。
2. 银行账户管理系统
使用C++的类模拟银行账户,实现账户创建、存款、取款和交易明细查询功能。
**代码实现:**cpp#include
class Transaction {public: string date; double amount;
Transaction(string date, double amount) { this->date = date; this->amount = amount; }};
class BankAccount {public: string accountNumber; string creationDate; double balance; vector
BankAccount(string accountNumber, string creationDate, double balance) { this->accountNumber = accountNumber; this->creationDate = creationDate; this->balance = balance; }
void deposit(double amount) { time_t now = time(0); tm* localTime = localtime(&now); string date = to_string(localTime->tm_year + 1900) + '-' + to_string(localTime->tm_mon + 1) + '-' + to_string(localTime->tm_mday); transactions.push_back(Transaction(date, amount)); balance += amount; }
void withdraw(double amount) { time_t now = time(0); tm* localTime = localtime(&now); string date = to_string(localTime->tm_year + 1900) + '-' + to_string(localTime->tm_mon + 1) + '-' + to_string(localTime->tm_mday); transactions.push_back(Transaction(date, -amount)); balance -= amount; }
void printTransactions() { time_t now = time(0); tm* localTime = localtime(&now); string currentDate = to_string(localTime->tm_year + 1900) + '-' + to_string(localTime->tm_mon + 1) + '-' + to_string(localTime->tm_mday); cout << 'Recent transactions:' << endl; for (int i = 0; i < transactions.size(); i++) { if (transactions[i].date >= currentDate) { cout << transactions[i].date << ': ' << transactions[i].amount << endl; } } }};
int main() { BankAccount account('1234567890', '2022-01-01', 1000.0); account.deposit(500.0); account.withdraw(200.0); account.printTransactions(); return 0;}
代码解释:
Transaction类表示一笔交易记录,包含日期和金额。-BankAccount类表示一个银行账户,包含账号、创建日期、余额和交易记录列表。-deposit方法实现存款功能,记录存款日期和金额,并更新余额。-withdraw方法实现取款功能,记录取款日期和金额,并更新余额。-printTransactions方法打印近一个月的交易记录。
希望本文能够帮助您理解C++实现有序表折半查找和银行账户管理的方法。
原文地址: https://www.cveoy.top/t/topic/f3Zp 著作权归作者所有。请勿转载和采集!