the purpose of %f

40 visualizaciones (últimos 30 días)
Umut Oskay
Umut Oskay el 5 de Abr. de 2020
Comentada: Umut Oskay el 5 de Abr. de 2020
i know what %d is but i want to know what is %f and is there any difference between %d and %f?

Respuesta aceptada

John D'Errico
John D'Errico el 5 de Abr. de 2020
Editada: John D'Errico el 5 de Abr. de 2020
They seem identical to me. See? The result is exactly the same. ;-)
sprintf('%d',pi)
ans =
'3.141593e+00'
sprintf('%f',pi)
ans =
'3.141593'
Or here:
sprintf('%d',137)
ans =
'137'
sprintf('%f',137)
ans =
'137.000000'
%d would typically be used to display signed integers, as in the second example, or in this next one.
sprintf('%10d',-137)
ans =
' -137'
sprintf('%10f',-137)
ans =
'-137.000000'
%f applies to floating point numbers.
The caveat is, if the number is actually a floating point number, but you used %d, then MATLAB must do something. Reading the help docs for sprintf, I found this comment:
If you specify a conversion that does not fit the data, such as a text conversion for a numeric value, MATLAB® overrides the specified conversion, using instead %e.
Now, go back to the first example I showed. Consider which format was used there.
  1 comentario
Umut Oskay
Umut Oskay el 5 de Abr. de 2020
thanks alo t

Iniciar sesión para comentar.

Más respuestas (1)

Walter Roberson
Walter Roberson el 5 de Abr. de 2020
On output, %d is intended for signed integer; %f is intended for fixed-point representation.
On input formats, such as textscan(), %d by itself is intended to read a signed integer that fits into 32 bits and is output as int32 data type, whereas %f is intended to read floating point numbers and return double precision. There are variations such as %d16 for 16 bit signed integers.
  3 comentarios
Walter Roberson
Walter Roberson el 5 de Abr. de 2020
For example, if you create an 8 bit integer, then you can either use it to store the numbers 0 to 255 (unsigned --> all non-negative) or -128 to 127 (signed, potentially negative)
Umut Oskay
Umut Oskay el 5 de Abr. de 2020
Thanks

Iniciar sesión para comentar.

Etiquetas

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by