1

folks! I've encountered a little problem: I'm doing a simple addition with three double values. The result has a smaller precision than the used values.

double minutes = 3;
minutes = minutes / (24.0*60.0);  // contains 0.00208333
double hours = 3;
hours = hours / 24.0; // contains 0.125
double days = 3; // contains 3 

double age = days + hours + minutes; // result is 3.12708 

I found no way to avoid this behaviour.

Micha
  • 5,117
  • 8
  • 34
  • 47
XQDev
  • 366
  • 4
  • 15

3 Answers3

5

Nothing seems to be wrong with the calculation as what the comments on your post said.

If you'd like to see more precision consider looking up setprecision()

Chris Wijaya
  • 1,276
  • 3
  • 16
  • 34
  • The calculation is correct, indeed. I validated this by using printf(). The loss of precision was been caused by outputting it by std::cerr or assigning it to a std::stringstream. setprecision did the trick. Thanks a lot! – XQDev Jun 20 '13 at 12:58
0

There is no problem. The significant figure of 0.00208333 and 3.12708 are both 6. This is a correct result.

qpalz
  • 71
  • 2
  • 7
0

Sometimes in order to get the value according to the desired precision we have to specify the limit of precision,here is my code which works fine ,hope it helps:

double minutes = 3;
minutes = minutes / (24.0*60.0);
double hours = 3;
hours = hours / 24.0; 
double days = 3;
double age = days + hours + minutes;
printf("%.8f",age);//here i have included the places of precision (.8)
0decimal0
  • 3,884
  • 2
  • 24
  • 39