1

I have a code as follows:

double a = 50e-12;
double b = 50.5e-12;
double c = b - a;
std::cout<<"value of a,b and c is : "<<a<<" " <<b<<" "<<c<<std::endl;

Now my output is : value of a,b and c is : 0.0000000001 0.0000000001 0.0000000000

I can see that my operands are rounded off and because of which I get a 0 as the output although I expect a 0.5.

Can someone help me with this.?

deeps
  • 21
  • 1

3 Answers3

6

Under the circumstances, it seems to me like it makes the most sense to print the result out using (C++'s approximation of) scientific notation:

#include <iostream>
#include <iomanip>

int main() { 
    double a = 50e-12;
    double b = 50.5e-12;
    double c = b - a;

    std::cout << std::scientific << c << "\n";
}

This produces about what you'd expect:

5.000000e-13

While you certainly can just print out all 13 or 15 digits (or whatever) in decimal, when your input is in (pseudo-) scientific notation, it probably makes the most sense to print the output the same way.

Jerry Coffin
  • 476,176
  • 80
  • 629
  • 1,111
1

Change the precision before printing your values:

#include <iomanip>
#include <limits>

std::cout << std::setprecision(std::numeric_limits<double>::digits10 + 1)
          << "value of a, b and c is : " << a << " " << b << " " << c << std::endl;
YSC
  • 38,212
  • 9
  • 96
  • 149
1

You can tell the output stream how many digits to display. Here's how you can tell it to use the max number of digits for a double.

#include <limits>    

cout.precision(std::numeric_limits<double>::max_digits10);
Buddy
  • 10,874
  • 5
  • 41
  • 58