以下是用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, 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;
}

以下是Bank类的实现:

#include <iostream>
#include <vector>
#include <ctime>
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类,包括账号、创建日期、余额和交易记录。可以通过deposit方法存钱,通过withdraw方法取钱,并记录交易日期和数目。可以通过printTransactionHistory方法查询近一个月的交易记录

一、用C++语言编程实现有序表的折半查找算法设计一个Bank类实现银行某账户的资金往来账目管理。程序要求完成以下操作。1	创建账户:包括账号、创建日期、余额。2	存钱:执行存钱操作并记录存钱日期和存钱数目。3	取钱:执行取钱操作并记录取钱日期和取钱数目。4	查询交易明细:查询近一个月的账户交易记录。

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

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