C++实现折半查找算法及银行账户管理系统
C++实现折半查找算法及银行账户管理系统
本文首先介绍了使用C++语言实现折半查找算法,然后设计了一个Bank类,用于管理银行账户的存取款、查询交易明细等功能。
一、折半查找算法
折半查找算法,也称为二分查找算法,是一种高效的查找算法,适用于已排序的数据集。
以下是使用C++语言编写的折半查找算法的实现:
#include <iostream>
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, 3, 5, 7, 9, 11, 13, 15};
int n = sizeof(arr) / sizeof(arr[0]);
int target = 7;
int result = binarySearch(arr, 0, n - 1, target);
if (result == -1) {
cout << 'Element not found.' << endl;
}
else {
cout << 'Element found at index ' << result << '.' << endl;
}
return 0;
}
该程序定义了一个binarySearch函数,用于在已排序数组arr中查找目标值target。函数返回目标值在数组中的索引,如果未找到则返回-1。
二、Bank类设计
以下是使用C++语言编写的Bank类的设计:
#include <iostream>
#include <string>
#include <vector>
#include <ctime>
using namespace std;
class Bank {
private:
string accountNumber;
string creationDate;
double balance;
vector<pair<time_t, double>> transactions;
public:
Bank(string accountNumber, string creationDate, double balance) {
this->accountNumber = accountNumber;
this->creationDate = creationDate;
this->balance = balance;
}
void deposit(double amount) {
balance += amount;
time_t currentTime = time(0);
transactions.push_back(make_pair(currentTime, amount));
}
void withdraw(double amount) {
if (balance >= amount) {
balance -= amount;
time_t currentTime = time(0);
transactions.push_back(make_pair(currentTime, -amount));
}
else {
cout << 'Insufficient balance.' << endl;
}
}
void printRecentTransactions() {
time_t currentTime = time(0);
for (int i = transactions.size() - 1; i >= 0; i--) {
time_t transactionTime = transactions[i].first;
double transactionAmount = transactions[i].second;
if (currentTime - transactionTime <= 30 * 24 * 60 * 60) {
cout << 'Date: ' << ctime(&transactionTime);
cout << 'Amount: ' << transactionAmount << endl;
}
}
}
};
int main() {
Bank bank('1234567890', '2021-01-01', 1000.0);
bank.deposit(500.0);
bank.withdraw(200.0);
bank.printRecentTransactions();
return 0;
}
该程序定义了一个Bank类,包含账号、创建日期、余额以及交易记录等属性,并提供了存款、取款以及打印最近交易记录等方法。
在主函数中,我们创建了一个Bank对象,并进行了存款、取款和打印最近交易记录的操作。
总结
本文介绍了使用C++语言实现折半查找算法,并设计了一个简单的银行账户管理系统。希望对您有所帮助!
原文地址: https://www.cveoy.top/t/topic/f3Zt 著作权归作者所有。请勿转载和采集!