So i have this code
template <typename T, typename T2>
void print (const T& a, const T2& b)
{
cout << a<<endl<<b<<endl ;
}
int main(){
float i=1.002;
float j=1.000;
print(i,j);
return 0;
}
the output is
1.002
1
what i dont get is why does cout remove the zeroes although i have specified them during initailisation , i know it wont make any difference but im just curious why does it happen.
1.000 == 1
.Because of the way the number is stored.
TheIEEE floating point representation does not have a notion of significant digits. The numbers 1.0 or 1.000 all look the same in the binary notation.
You have to specify a precision when printing.
Python for instance does a type Decimal that behaves like you want.
Expecting your code to print those trailing zeros is no different than expecting it to print 5.0 - 4.0
just because you initialized the variable as float j = 5.0 - 4.0;
.
From the floating-point representation perspective, there's no such thing as "I specified trailing zeros during initialization". Floating-point numbers are not strings. They are numbers. And there are infinite different ways to express the same number as a sequence of human-readable characters in your program's text. In the source code of the program 1.000
is the same as 1.00
and is the same as 0.1e1
- they all represent the same number.
This means that when the time comes to convert a floating-point number back to the textual representation for cout
, the library will not know (and will not care) what kind of text you used originally. You can affect the textual output by changing the precision, width and other format details (like use scientific format etc.), but there's no such thing as "output it the same way I wrote it in the source code".
Why would it print 1.000
instead of 1.0000000000000000
? Both of those numbers are the same exact bits in memory. (In other words, a float value is stored as 32-bits in a very specific format. No matter if it is 1.0 or -59.12391 it is 32-bits of data in memory somewhere.)
If you want it to be printed in a certain way, use formatting specifiers such as setw()
(don't forget to #include<iomanip>
) to format your cout
output a certain way.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.