the purpose of %f

56 次查看(过去 30 天)
Umut Oskay
Umut Oskay 2020-4-5
i know what %d is but i want to know what is %f and is there any difference between %d and %f?

采纳的回答

John D'Errico
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
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
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 CenterFile Exchange 中查找有关 Logical 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by