1

I have a seemingly simple c++ issue that's bothering me. The output of the code

#include <iostream>
using namespace std;

int main() {
    // your code goes here
    double c = 9.43827  * 0.105952 ; 
    cout << c << endl ;
    return 0;
}

is 1. Just 1. I guess this is due to precision loss based on how doubles are stored in c++ but surely there must be a way in c++ to get some sort of precision (2 or 3 decimal places) in the result.

reayn3
  • 363
  • 5
  • 16

3 Answers3

1

It's not precision loss in storage, it's precision loss in converting to text. The stream inserter for double defaults to six significant digits. The product here, 1.000003583, rounded to six significant digits, is 1.00000. In addition, if you haven't set showpoint, the trailing zeros and the decimal point will be suppressed, so you'll see a bare 1. To get the decimal point to show, use std::cout << std::showpoint << c << '\n';. To see more significant digits, use std::cout << std::setprecision(whatever) << c << '\n';, where whatever is the number of digits you want the formatter to use.

Pete Becker
  • 74,985
  • 8
  • 76
  • 165
  • Awesome! Thank you for the clarification @PeteBecker. That said, this is a great show of how different programming languages have interesting nuances. Who would have thought to truncate to only 6 significant digits. Why not 10, or 11 or as much precision as the compiler can provide...Then the programmer can cut out what she does not need. – reayn3 Nov 27 '15 at 02:07
  • 1
    @reayn3 - the simplest answer is that that's how C does it. – Pete Becker Nov 27 '15 at 02:09
  • Haha. I guess so @PeteBecker. Thanks anyhow – reayn3 Nov 27 '15 at 02:11
0
#include <stdio.h>

int main() {
  // your code goes here                                                                             
  double c = ((double)9.43827)  * 0.105952 ;
  for(int i = (sizeof(double)*8)-1; i >= 0; i-- ) {
    printf("%ld", (*(long*)&c>>i)&1);
  }
}

If you run that, you can clearly see the bit representation of your double is not the integer value 1. You're not losing any data.

0011111111110000000000000000001111000001110100001010001001001001

but it is very close to 1, so that's what gets printed out.

xaxxon
  • 19,189
  • 5
  • 50
  • 80
-1

Try using cout<<setprecision(12)<<c<<endl;

setprecision sets the decimal precision to be used to format floating-point values on output operations.

source

Max Pain
  • 1,217
  • 7
  • 19
  • 33
  • Bing: 9.43827 * 0.105952 = 1.00000358304, setprecision(12) = 1.00000358305 – msmith81886 Nov 27 '15 at 01:52
  • Thanks @Max Pain. What i really need to do is to pass the result of that double multiplication into another double. using cout was just to illustrate the issue. How can i pass a higher precision result to another double? – reayn3 Nov 27 '15 at 01:56