C++ float and double Different Precisions For Different Variables
#include <iostream>
#include <iomanip>
int main() {
float a = 1.123456789f;
double b = 1.123456789;
std::cout << std::setprecision(10) << "Float: " << a << std::endl;
std::cout << std::setprecision(20) << "Double: " << b << std::endl;
return 0;
}
This code demonstrates the usage of float
and double
data types in C++. The float
variable a
is assigned the value 1.123456789f
explicitly as a float, while the double
variable b
is assigned the value 1.123456789
implicitly as a double.
The program then uses std::setprecision()
from the <iomanip>
library to set the precision for output. It displays the value of the float
variable a
with a precision of 10 decimal places and the value of the double
variable b
with a precision of 20 decimal places using std::cout
.
The output demonstrates the difference in precision between float
and double
types in C++, showcasing how a float
can store up to approximately 7 decimal digits of precision while a double
can store up to about 15-16 decimal digits of precision.