C ++双精度和四舍五入 [英] C++ double precision and rounding off

查看:164
本文介绍了C ++双精度和四舍五入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下问题:



double a = 6.005;双b = 5.995;



我想设置点后两位数的精度,例如



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



我该如何做?

解决方案

;圆形显示是另一回事。



我认为这是错误的。结果完成后,您应该希望获得所有精度,并担心舍入显示。



更新:



您不应该使用双打来代表货币。上次我看,C ++是面向对象的语言。您应该创建一个抽象的金钱,做正确的事情,并将这些细节从类的客户抽象。



您可以创建一个Money类,管理私人表示如果你以美元工作,那么货币就是美分。使用整数进行所有的计算,并在结束时渲染。


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?

解决方案

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.

这篇关于C ++双精度和四舍五入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆