the purpose of %f
40 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Umut Oskay
am 5 Apr. 2020
Kommentiert: Umut Oskay
am 5 Apr. 2020
i know what %d is but i want to know what is %f and is there any difference between %d and %f?
0 Kommentare
Akzeptierte Antwort
John D'Errico
am 5 Apr. 2020
Bearbeitet: John D'Errico
am 5 Apr. 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.
Weitere Antworten (1)
Walter Roberson
am 5 Apr. 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 Kommentare
Walter Roberson
am 5 Apr. 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)
Siehe auch
Kategorien
Mehr zu Text Files finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!