the purpose of %f
47 次查看(过去 30 天)
显示 更早的评论
i know what %d is but i want to know what is %f and is there any difference between %d and %f?
0 个评论
采纳的回答
John D'Errico
2020-4-5
编辑:John D'Errico
2020-4-5
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 个)
Walter Roberson
2020-4-5
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 个评论
Walter Roberson
2020-4-5
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)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Text Files 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!