Here's my code:
float x = 21.195;
printf("%.2f\n", x);
printf("%.2f\n", 21.195);
I would expect both print statements to have identical output, but instead, the first prints 21.19
, and the second prints 21.20
.
Could someone explain why the output is different?
So, you can see here that %d is used for integers, %f for floats and %c for characters. As simple as that!
%g. It is used to print the decimal floating-point values, and it uses the fixed precision, i.e., the value after the decimal in input would be exactly the same as the value in the output. %p. It is used to print the address in a hexadecimal form.
Float and double are both widely used data types in programming that have the ability to store decimal or floating-point numbers. The only difference between them is the precision. A float is a 32-bit IEEE 754 single-precision floating-point number.
For type long double, the correct format specifier is %Lf. For input using the scanf family of functions, the floating-point format specifiers are %f, %lf, and %Lf. These require pointers to objects of type float, double, and long double, respectively.
The values are different. The first is a float
, which is typically 4 bytes. The second is a double
, which is typically 8 bytes.
The rules for rounding are based on the third digit after the decimal place. So, in one case, the value is something like 21.19499997 and the other 21.1950000000001, or something like that. (These are made up to illustrate the issue with rounding and imprecise numeric formats.)
By default 21.195 is a double.
If you want a float, write :
21.195F
or
(float)21.195
Regards
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With