-2

C++

float f = 0.123456789;
double d = 0.123456789;

cout << "float = " << f << endl;
cout << "double = " << d << endl;

Output

float = 0.123457
double = 0.123457

Why?
How to use double and long double?
Is there a variable larger than long double?

jony tony
  • 20
  • 3
  • 4
    Read up on stream manipulators such as `std::setw` and `std::fixed`. – Ron Sep 11 '18 at 10:16
  • Number of digits in displayed floating point number is configured on the `std::cout` side and is not necessarily dependent on number of bytes representing that value. – pptaszni Sep 11 '18 at 10:16
  • https://stackoverflow.com/questions/554063/how-do-i-print-a-double-value-with-full-precision-using-cout – halfelf Sep 11 '18 at 10:20
  • why what? Please explain what else you expected – 463035818_is_not_an_ai Sep 11 '18 at 10:21
  • duplicate in C: [Float and double precision in C](https://stackoverflow.com/q/32291052/995714) – phuclv Sep 11 '18 at 10:34
  • My answer to another question may be of relevance: https://stackoverflow.com/questions/50968737/comparison-of-double-long-double-float-and-float128/50970282#50970282 – Eljay Sep 11 '18 at 12:20
  • 1
    @Eljay , That's a best answer, if you post it as answer, i well give you (best answer). thank you very much. – jony tony Sep 11 '18 at 12:57

1 Answers1

1

What you're seeing is not exactly what the content of the variables is, but what the standard ouptut stream outputs after rounding them. Look up the std::setprecision function from the header <iomanip>.

A quick test on Coliru with:

float f = 0.123456789;
double d = 0.123456789;

std::cout << "float = " << std::setprecision(13) << f << std::endl;
std::cout << "double = " << std::setprecision(13) << d << std::endl;

yields the output:

float = 0.1234567910433

double = 0.123456789

It shows that indeed, float and double are not the same type in terms of which numbers they can represent. (Hint: this is not even the exact number stored in the float, only the one rounded to 13 significant digits).

Community
  • 1
  • 1
JBL
  • 12,588
  • 4
  • 53
  • 84
  • thank you, but 1- what is 10433 after 0.12345679 in float? 2- float 6 or 9 decimal? – jony tony Sep 11 '18 at 10:42
  • I would suggest that you look up and learn more about the floating types themselves as your questions touch on a more general topic. As I mentioned in my question, they're not able to represent every single real number in an exact manner. – JBL Sep 11 '18 at 10:48