0

As like,

AC = sqrt((AB*AB)+(BC*BC)); 

BD = sqrt((BC*BC)+(CD*CD));

(where all variables are double type)

Here, i want the value of AC and BD fixed with 2 digits after decimal point and then I want to add AC and BD. Now, if i take (3 digits after decimal point) AC=4.564 and BD=4.789 the the result after adding them is 9.351. Again if i take (2digits after decimal point) AC=4.56 and BD=78 then the result after adding them is 9.34. Now if i print both result fixed with 2 digits after decimal point then it shows 9.35 and 9.34 respectively. But I want 9.34 as result.

Ashish Deb
  • 25
  • 1
  • 8
  • Use `setprecision()` when printing them. – Barmar Sep 28 '16 at 19:50
  • Please clarify your specific problem or add additional details to highlight exactly what you need. As it's currently written, it’s hard to tell exactly what you're asking. See the How to Ask page for help clarifying this question. – too honest for this site Sep 28 '16 at 19:54
  • Let, I found AC=4.564 and BD=4.789; Now, if i want to add AC with BD then the result is 9.351 and if now i print the number fixed with 2 digits after decimal point then it will show 9.35. But if i take AC=4.56 and BD=4.78 then the result is 9.34. And i want 9.34 as result. – Ashish Deb Sep 28 '16 at 20:49

2 Answers2

0

Two decimals of accuracy:

  1. Multiply by 100
  2. Add 0.5
  3. Round down to closest integer
  4. Divide by 100

But if you happen to end up with an integer value, you won't have "2 digits after decimal point"

Stormwind
  • 814
  • 5
  • 9
-1

If you're trying to output double values with 2 digits after the decimal then use modifiers to a stream like so:

std::cout << std::setprecision (2) << std::fixed << AC;

This will output a fixed point representation of the floating point number with 2 digits of precision.

Also, you should look at the round, ceil and floor functions and use them as follows:

ans = round (AC * 100.0) / 100.0

to do what you want. You'll find that you cannot represent all numbers as just two digits after the decimal so any comparisons you make should test for closeness of the answer to the target by +/- a small epsilon to the target value.

If you're trying to use the values computed for financial computation then this is very dangerous to do with the double type because certain values cannot be represented exactly with a limited number of bits of precision. You will suffer from accumulation of errors when performing financial computation with float/double types.

Jess
  • 16
  • 3