Reading and Writing Floating-point Numbers
In this tutorial, we will learn how to read and write single and double precision floating-point numbers.
In this tutorial, we will learn how to read and write single and double precision floating-point numbers.
We have learned in our tutorial on Capabilities of Format Specifiers, that a single precision floating-point number can be read or written using %e
, %f
, or %g
format specifiers. Recall that the %e
format specifier is used to read or write a single precision floating-point number in scientific notation, %f
in decimal notation, and %g
in either scientific or decimal notation depending upon the size of the number. It’s important to note that reading or writing a double precision floating-point number requires a slightly different format specifier.
To read a double precision value, we need to add the letter “l” (small l) in front of e, f, or g. Here’s an example:
double x;
scanf(“%lf”, &x);
It is worth noting that adding l in front of e, f, or g has no effect in the printf function. You can use any of the format specifiers without the letter “l” to print float or double values.
To read or write a value of type long double, we need to add the letter “L” (capital L) in front of e, f, or g. Here’s an example:
long double x;
scanf(“%Lf”, &x);
printf(“%Lf”, &x);
Inside the printf function, it’s mandatory to use %Lf
as the format specifier to print a long double value.
This tutorial explains how to read and write floating-point numbers in both single and double precision. It provides information on the format specifiers to use for each type of floating-point number and highlights the differences when working with double precision or long double values.
Leave a comment