the purpose of %f

56 ビュー (過去 30 日間)
Umut Oskay
Umut Oskay 2020 年 4 月 5 日
コメント済み: 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 件のコメント
Umut Oskay
Umut Oskay 2020 年 4 月 5 日
thanks alo t

サインインしてコメントする。

その他の回答 (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)
Umut Oskay
Umut Oskay 2020 年 4 月 5 日
Thanks

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by