C++双精度和四舍五入

发布于 2024-11-27 11:36:04 字数 162 浏览 2 评论 0原文

我有以下问题:

double a = 6.005; double b = 5.995;

我想设置点后双精度 2 位数字,例如

double c = a+b;// 我想得到 11.99 而不是 12.00

我该怎么做?

I have the following problem:

double a = 6.005; double b = 5.995;

I want to set precision of doubles 2 digits after point, for example

double c = a+b;// I would like to get 11.99 not 12.00.

How can I do this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

伴我老 2024-12-04 11:36:05

您可能应该使用定点数字:

unsigned int a = 600;
unsigned int b = 599;

unsigned int c = a + b;

unsigned int make_fixed(double d) { return d * 100; }

void print_fixed(unsigned int n) { std::cout << n/100 << "." << n%100; }

You should probably use fixed point numbers:

unsigned int a = 600;
unsigned int b = 599;

unsigned int c = a + b;

unsigned int make_fixed(double d) { return d * 100; }

void print_fixed(unsigned int n) { std::cout << n/100 << "." << n%100; }
恋竹姑娘 2024-12-04 11:36:05

不,您要么需要一一调整所有值(mul 乘 100,取 int 部分,div 乘 100),或者需要编写自己的 MySpecialDouble 类(在幕后执行相同的操作)。

No, you either need to adjust all values one by one (mul by 100, take int part, div by 100), or you need to write your own MySpecialDouble class (that does the same just behind the scene).

手心的海 2024-12-04 11:36:04

精度是一回事,但又是一回事。圆形显示则完全是另一回事。

我认为这是错误的。您应该希望获得尽可能多的精度,并担心结果完成后显示的舍入问题。

更新:

您不应该使用双精度数来表示货币。上次我看的时候,C++ 是一种面向对象的语言。您应该为 Money 创建一个抽象,它可以做正确的事情,并将这些细节从类的客户端中抽象出来。

如果您使用的是美元,则可以创建一个 Money 类来管理以美分为单位的货币的私有表示形式。使用整数进行所有计算并在最后渲染。

Precision is one thing; rounded for display is quite another.

I think this is wrong headed. You should want all the precision you can get and worry about rounding for display when the results are complete.

UPDATE:

You should not be representing currency using doubles. Last time I looked, C++ was an object-oriented language. You should create an abstraction for Money that does the right thing and abstracts these details away from clients of the class.

You can create a Money class that manages a private representation of the currency as cents if you're working in dollars. Do all your calculations using integers and render at the end.

情魔剑神 2024-12-04 11:36:04

我想设置点后双精度2位数

只需乘以 100 并使用整数即可。

I want to set precision of doubles 2 digits after point

Just multiply by 100 and use integers then.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文