Так, по сути, я делаю книгу 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
Реализация округления банкира C ++ ⇐ C++
Программы на C++. Форум разработчиков
1738707586
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
Подробнее здесь: [url]https://stackoverflow.com/questions/69146695/implementing-bankers-rounding-c[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия