Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what's the difference between printf a floating-point variable and constant?

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?

like image 422
Tamara Avatar asked Oct 24 '15 18:10

Tamara


People also ask

Can I use %d for float?

So, you can see here that %d is used for integers, %f for floats and %c for characters. As simple as that!

What does %g mean C?

%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.

Is float and floating-point the same?

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.

What means %LF C?

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.


2 Answers

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.)

like image 179
Gordon Linoff Avatar answered Oct 11 '22 20:10

Gordon Linoff


By default 21.195 is a double.

If you want a float, write :

21.195F

or

(float)21.195

Regards

like image 39
Emmanuel DURIN Avatar answered Oct 11 '22 19:10

Emmanuel DURIN