C++实现银行家四舍五入

问题描述 投票:0回答:3

所以本质上我正在写一本 C++ 书,其中一个练习是修改书中的示例以使用银行家舍入。就上下文而言,银行四舍五入是以分数为单位的四舍五入到最接近的偶数。我花了几个小时试图找出如何实现它,但没有任何效果。下面列出了书中的代码。

// Ex. 5.31: DollarAmount.h
// DollarAmount class gets two parameter constructor
#include <string>
#include <cmath>

class DollarAmount {
public:
    // initialize amount from an int64_t value
    explicit DollarAmount(int64_t dollars, int64_t cents) : amount{dollars * 100 + cents} { }

    // add right's amount to this object's amount
    void add(DollarAmount right) {
        // can access private data of other objects of the same class
        amount += right.amount;
    }

    // subtract right's amount from this object's amount
    void subtract(DollarAmount right) {
        // can access private data of other objects of the same class
        amount -= right.amount;
    }

    // divide amount by the divisor
    void divide(int divisor) {
        amount = (amount + divisor / 2) / divisor;
    }

    // uses integer arithmetic to calculate interest amount,
    // then calls add with the interest amount
    void addInterest(int rate, int divisor) {
        // create DollarAmount representing the interest
        DollarAmount interest {
            ((amount * rate + divisor / 2) / divisor) / 100, // dollars
            ((amount * rate + divisor / 2) / divisor) % 100 // cents
        };

        add(interest); // add interest to this object's amount
    }

    // return a string representation of a DollarAmount object
    std::string toString() const {
        std::string dollars{std::to_string(amount / 100)};
        std::string cents{std::to_string(std::abs(amount % 100))};
        return dollars + "." + (cents.size() == 1 ? "0" : "") + cents;
    }
private:
    int64_t amount{0}; // dollar amount in pennies
};

我已经尝试了几件事,但我将代码恢复到原来的形式,因为其他的不起作用。当前算法使用正常舍入。作者并没有很好地解释舍入系统。

编辑:这也是使用的主程序。

// Ex. 5.31: Interest.cpp
// Compound-interest calculations with class DollarAmount and integers.
#include <iostream>
#include <iomanip>
#include <string>
#include "DollarAmount.h"
using namespace std;

int main() {
    DollarAmount d1{123, 45}; // $123.45
    DollarAmount d2{15, 76}; // $15.76

    cout << "After adding d2 (" << d2.toString() << ") into d1 ("
        << d1.toString() << "), d1 = ";
    d1.add(d2); // modifies object d1
    cout << d1.toString() << "\n";

    cout << "After subtracting d2 (" << d2.toString() << ") into d1 ("
        << d1.toString() << "), d1 = ";
    d1.subtract(d2); // modifies object d1
    cout << d1.toString() << "\n";

    cout << "After subtracting d1 (" << d2.toString() << ") from d2 ("
        << d2.toString() << "), d2 = ";
    d2.subtract(d1); // modifies object d2
    cout << d2.toString() << "\n";

    cout << "After dividing d1 (" << d1.toString() << ") by 2, d1 = ";
    d1.divide(2); // modifies object d1
    cout << d1.toString() << "\n\n";
    
    cout << "Enter integer interest rate and divisor. For example:\n"
        << "for     2%, enter:    2 100\n"
        << "for   2.3%, enter:   23 1000\n"
        << "for  2.37%, enter:  237 10000\n"
        << "for 2.375%, enter: 2375 100000\n";
    int rate; // whole-number interest rate
    int divisor; // divisor for rate
    cin >> rate >> divisor;

    DollarAmount balance{1000, 0}; // initial principal amount in pennies
    cout << "\nInitial balance: " << balance.toString() << endl;

    // display headers
    cout << "\nYear" << setw(20) << "Amount on deposit" << endl;

    // calculate amount on deposit for each of ten years
    for (unsigned int year{1}; year <= 10; year++) {
        // increase balance by rate % (i.e., rate / divisor)
        balance.addInterest(rate, divisor);

        // display the year and the amount
        cout << setw(4) << year << setw(20) << balance.toString() << endl;
    }
}

我目前正在使用输入 2 100 和 5 1000000 进行测试。

我尝试创建一个条件,如果表达式 mod 1 为 0.5,如果为真,则使用正常分;如果表达式 mod 2 为偶数,则使用正常分加零;如果表达式 mod 2 为奇数,则使用正常分加零。结果变得很混乱,甚至不起作用,而且当我测试它时,不知何故摆脱了所有的美分。对于银行家舍入算法,输入 2 100 应返回 10 年的 1218.98,而 5 1000000 应始终返回 1000,因为它四舍五入到最接近的偶数,向下舍入。

编辑2:我对代码做了一些修改,我想我已经想到了我将使用的算法。这是修改后的源代码。

// Ex. 5.31: DollarAmount.h
// DollarAmount class gets two parameter constructor
#include <string>
#include <iostream>
#include <cmath>

class DollarAmount {
public:
    // initialize amount from an int64_t value
    explicit DollarAmount(int64_t dollars, int64_t cents) : amount{dollars * 100 + cents} { }

    // add right's amount to this object's amount
    void add(DollarAmount right) {
        // can access private data of other objects of the same class
        amount += right.amount;
    }

    // subtract right's amount from this object's amount
    void subtract(DollarAmount right) {
        // can access private data of other objects of the same class
        amount -= right.amount;
    }

    // divide amount by the divisor
    void divide(int divisor) {
        amount = (amount + divisor / 2) / divisor;
    }

    // uses integer arithmetic to calculate interest amount,
    // then calls add with the interest amount
    void addInterest(int rate, int divisor) {
        // create DollarAmount representing the interest
        DollarAmount interest {
            ((amount * rate + divisor / 2) / divisor) / 100, // dollars
            ((amount * rate + divisor / 2) / divisor) % 100 // cents
        };

        if (static_cast<int64_t>((((amount * rate + divisor / 2) / divisor) % 1) * 10) == 5) {
            if (interest.amount % 2 == 1) {
                interest.amount--;
            }
            
            std::cout << "test";
        }

        add(interest); // add interest to this object's amount
    }

    // return a string representation of a DollarAmount object
    std::string toString() const {
        std::string dollars{std::to_string(amount / 100)};
        std::string cents{std::to_string(std::abs(amount % 100))};
        return dollars + "." + (cents.size() == 1 ? "0" : "") + cents;
    }
private:
    int64_t amount{0}; // dollar amount in pennies
};

所以本质上我的计划是正常创建利息对象,但然后我检查是否满足银行家的舍入条件,然后检查interest.amount变量%2 == 1,这意味着它没有舍入到最接近的偶数整数。如果满足此条件,则会减少interest.amount 变量。这似乎有点混乱,但由于似乎没有更简单的方法,我想我会尝试这种方法。问题是 if 语句当前无法检查是否需要银行四舍五入。

编辑3:添加评论

// Ex. 5.31: DollarAmount.h
// DollarAmount class gets two parameter constructor
#include <string>
#include <iostream>
#include <cmath>

class DollarAmount {
public:
    // initialize amount from an int64_t value
    explicit DollarAmount(int64_t dollars, int64_t cents) : amount{dollars * 100 + cents} { }

    // add right's amount to this object's amount
    void add(DollarAmount right) {
        // can access private data of other objects of the same class
        amount += right.amount;
    }

    // subtract right's amount from this object's amount
    void subtract(DollarAmount right) {
        // can access private data of other objects of the same class
        amount -= right.amount;
    }

    // divide amount by the divisor
    void divide(int divisor) {
        amount = (amount + divisor / 2) / divisor;
    }

    // uses integer arithmetic to calculate interest amount,
    // then calls add with the interest amount
    void addInterest(int rate, int divisor) {
        // create DollarAmount representing the interest
        DollarAmount interest {
            ((amount * rate + divisor / 2) / divisor) / 100, // dollars
            ((amount * rate + divisor / 2) / divisor) % 100 // cents
        };

        // banker's rounding special case
        std::cout << (((amount * rate + divisor / 2) / divisor) % 1) * 10 << std::endl;
        if (static_cast<int64_t>((((amount * rate + divisor / 2) / divisor) % 1) * 10) == 5) {
            // if interest.amount is odd, implying normal rounding deviated from banker's rounding
            if (interest.amount % 2 == 1) {
                interest.amount--; // deincrement interest.amount to account for banker's rounding
            }

            std::cout << "test";
        }

        add(interest); // add interest to this object's amount
    }

    // return a string representation of a DollarAmount object
    std::string toString() const {
        std::string dollars{std::to_string(amount / 100)};
        std::string cents{std::to_string(std::abs(amount % 100))};
        return dollars + "." + (cents.size() == 1 ? "0" : "") + cents;
    }
private:
    int64_t amount{0}; // dollar amount in pennies
};

编辑4:好的,所以我想通了,我将使用正常的四舍五入,然后检查是否需要银行四舍五入,然后如果是,并且interest.amount是奇数,这意味着它偏离了银行四舍五入,它减少了它。剩下的唯一问题是我的 if 语句检查是否需要银行家四舍五入不起作用。

c++ c++11 c++14
3个回答
0
投票

就这样:

// Ex. 5.31: DollarAmount.h
// DollarAmount class gets two parameter constructor
#include <string>
#include <cmath>
#include <iostream>

class DollarAmount {
public:
    // initialize amount from an int64_t value
    explicit DollarAmount(int64_t dollars, int64_t cents) : amount{dollars * 100 + cents} { }

    // add right's amount to this object's amount
    void add(DollarAmount right) {
        // can access private data of other objects of the same class
        amount += right.amount;
    }

    // subtract right's amount from this object's amount
    void subtract(DollarAmount right) {
        // can access private data of other objects of the same class
        amount -= right.amount;
    }

    // divide amount by the divisor
    void divide(int divisor) {
        amount = (amount + divisor / 2) / divisor;
    }

    // uses integer arithmetic to calculate interest amount,
    // then calls add with the interest amount
    void addInterest(int rate, int divisor) {
        // create DollarAmount representing the interest
        DollarAmount interest {
            ((amount * rate + divisor / 2) / divisor) / 100, // dollars
            ((amount * rate + divisor / 2) / divisor) % 100 // cents
        };

        add(interest); // add interest to this object's amount
    }

    // return a string representation of a DollarAmount object
    std::string toString() const {
        std::string dollars{std::to_string(amount / 100)};
        std::string cents{std::to_string(std::abs(amount % 100))};
        return dollars + "." + (cents.size() == 1 ? "0" : "") + cents;
    }

    void bankersRounding() {

        std::cout << "money: " << amount << " cents" << std::endl;
        int dollarsPart = amount/100;
        int penniesPart = amount%100;
        std::cout << " - dollars: " << dollarsPart << std::endl;
        std::cout << " - pennies: " << penniesPart << std::endl;

        // if it is equally distant from upper and lower integers,
        // then apply banker's rounding
        if (penniesPart==50)
        {
            // if the lower integer is zero, then round down to zero
            if(dollarsPart==0)
            {
                std::cout << "it is zero" << std::endl;
                amount -= 50;
            }
            // if the lower integer is even, then round down
            else if ((dollarsPart%2)==0)
            {
                std::cout << "even" << std::endl;
                amount -= 50;
            }
            // else the lower integer is odd, so round up
            else {
                std::cout << "odd" << std::endl;
                amount += 50;
            }
        }
    }
private:
    int64_t amount{0}; // dollar amount in pennies

};


int main()
{
    DollarAmount d1(0, 0);
    DollarAmount d2(0, 50);

    d1.add(d2);

    d1.bankersRounding();

    std::cout << "final: " << d1.toString() << std::endl;

    return 0;
}

0
投票

这是我对银行家回合的实现。我检查了

sth.5
的情况,并将其四舍五入为奇数以返回不同的值。惰性评估有助于提高性能,但我忽略了(可能不是)实现银行家回合的最高效方法。

int bankersRound(double x) {
    double r;
    if(((x - std::floor(x)) == 0.5) && (std::fmod(std::round(x), 2.0) != 0)) {
        r = std::round(x) - 1.0;
    }
    else{
        r = std::round(x);
    }
    return (int)r;
}

-3
投票

我不确定你在哪一点被困住了,但也许你正在寻找这样的东西:

nearest_even=round(x/2)*2

我认为这是“银行四舍五入”的一个非常简单的实现。

© www.soinside.com 2019 - 2024. All rights reserved.