Реализация округления банкира C ++C++

Программы на C++. Форум разработчиков
Ответить
Anonymous
 Реализация округления банкира C ++

Сообщение Anonymous »

Так, по сути, я делаю книгу C ++, и одно из упражнений - изменить пример из книги для использования округления банкира. Для контекста, округление банкира - это то, где в дробных центах вы окружаете ближайшее ровное целое число. Я часами старался выяснить, как его реализовать, но для меня ничего не сработало. Код из книги перечислен ниже. < /P>
// Ex. 5.31: DollarAmount.h
// DollarAmount class gets two parameter constructor
#include
#include

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
};
< /code>
Я пробовал несколько вещей, но я вернул код обратно в его исходную форму, так как другие не работали. Алгоритм тока использует нормальное округление. Автор действительно не очень хорошо объяснил систему округления.// Ex. 5.31: Interest.cpp
// Compound-interest calculations with class DollarAmount and integers.
#include
#include
#include
#include "DollarAmount.h"
using namespace std;

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

cout

Подробнее здесь: https://stackoverflow.com/questions/691 ... rounding-c
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «C++»