0

For the following code:

#include <iostream>
using namespace std;
class Hall
{
 public:
 double cost;
};
int main()
{
 Hall hall;
 hall.cost=10000.50;
 cout<<hall.cost;
 return 0;
}

Why does this code output 10000.5 and not 10000.50, can someone explain the logic behind this?

proglove
  • 15
  • 5
  • Hmm... I found other questions regarding [how to get the zero to appear](https://stackoverflow.com/questions/13728425/print-double-with-precision-4-using-cout), but not one asking why. In other words, I found related questions, but not a duplicate. – JaMiT Mar 27 '21 at 15:46
  • 1
    *can someone explain the logic behind this?* The code did not ask to print the trailing zeroes. – Eljay Mar 27 '21 at 16:29

3 Answers3

2

can someone explain the logic behind this?

The default behaviour is not show any trailing zeroes.

eerorika
  • 232,697
  • 12
  • 197
  • 326
1

double (and floating-point variables in general) don't store a specific spelling of the number (base-10 or otherwise). That would be way too inefficient, and the ability to store meaningless zeroes would waste memory.

Instead, the numbers are encoded in a certain binary format. Printing them reproduces the base-10 spelling from binary.

HolyBlackCat
  • 78,603
  • 9
  • 131
  • 207
1

By default, C++ does not display trailing zeros, however the standard library <iomanip> can be used along with std::fixed from <iostream>. Here is an example:

#include <iostream>
#include <iomanip>
int main() {
  double myVar = 123.4;
  std::cout << std::fixed << std::setprecision(2); // 2 trailing digits
  std::cout << myVar << std::endl;
  return 0;
}
19UV
  • 111
  • 6