开发者

How to treat a double 3.14567 as a 3.14 (i.e with a given percision)

I was wondering if there is any way in c++ to treat a double with a given precision. for example, the number 3.1345 will be considered as 3.13 and the number 0.009 will be considered as 0 (precision of 2 after the dot).

I need that it will be applied on mathematical operations. for example:

double a = 0.009;
double b = 3.12345

//a should be considered as 0, b as 3.12

double c = a*b // should output 0.
double d = a+b // should output 3.12

s开发者_JAVA百科ince the function setprecision() is for std i was wondering if there is any other function to do that.

thanks


That's not going to work correctly with doubles, ever. Doubles are binary fractions, they don't have decimals or decimal precision. Read The Floating-Point Guide for details.

If you need specific decimal behaviour, you'll have to drop doubles and use a decimal data type. You may find double-based solutions that appear to work, but you'll always hit cases where it won't.


The easiest way:

int a100 = int(a*100);
int b100 = int(b*100);
int c100 = a100 * b100; // Will be 0
int d100 = a100 + b100; // Will be 312


double a = 3.12345; double b = ((int) a*100) / 100.0;


have a look at floor() and ceil()

http://www.cplusplus.com/reference/clibrary/cmath/floor/

a=floor(a); b=floor(b*100)/100;

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜